473,382 Members | 1,705 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Quick Filter Dictionary

Hi,
I have a dictionary which may contain various keys/values, however,
it will always contain 'name' and 'age' keys.

This dictionary is kept inside a class, such as....

class Person:
def __init__(self, name, age):
self.data = {'name' : name, 'age' : age}

def getData(self, includeNameAge=False):
if includeNameAge: return self.data
tmp = <shallow or deep copy of 'data'>
del tmp['name']
del tmp['age']
return tmp

The getdata method should return the data stored for the
person, however, it should be able to return the data excluding the
'name' and 'age'. Any suggestions on how to best implement this?
Keep in mind this sample code is meant to be an example, I realize
that a person would probably always want the name and age returned.

thanks

Mar 14 '07 #1
3 3309
On Mar 14, 7:29 am, "abcd" <codecr...@gmail.comwrote:
Hi,
I have a dictionary which may contain various keys/values, however,
it will always contain 'name' and 'age' keys.

This dictionary is kept inside a class, such as....

class Person:
def __init__(self, name, age):
self.data = {'name' : name, 'age' : age}

def getData(self, includeNameAge=False):
if includeNameAge: return self.data
tmp = <shallow or deep copy of 'data'>
del tmp['name']
del tmp['age']
return tmp

The getdata method should return the data stored for the
person, however, it should be able to return the data excluding the
'name' and 'age'. Any suggestions on how to best implement this?
Keep in mind this sample code is meant to be an example, I realize
that a person would probably always want the name and age returned.

thanks

I guess one solution might be....

def getData(self, includeNameAge=False):
if includeNameAge: return self.data
return dict(filter(lambda item: item[0] not in ('name', 'age'),
self.data.items()))

any other suggestions, improvements?

Mar 14 '07 #2
abcd a écrit :
On Mar 14, 7:29 am, "abcd" <codecr...@gmail.comwrote:
>Hi,
I have a dictionary which may contain various keys/values, however,
it will always contain 'name' and 'age' keys.

This dictionary is kept inside a class, such as....

class Person:
Do yourself a favor : use new-style classes:
class Person(object):
> def __init__(self, name, age):
self.data = {'name' : name, 'age' : age}
You may improve this part with kwargs:

def __init__(self, name, age, **kw):
kw.update(name=name, age=age)
self.data = kw

Also, and FWIW, object attributes are stored in self.___dict__. Do you
have a compelling reason to use yet another 'data' dict ?
> def getData(self, includeNameAge=False):
if includeNameAge: return self.data
tmp = <shallow or deep copy of 'data'>
tmp = self.data.copy()
> del tmp['name']
del tmp['age']
return tmp
The problem with this implementation (as well as for the other below) is
that in the first case you return a reference to the data dict itself,
while in the second case you return a new dict.

p = Person('bibi', 42, foo='bar')
data = p.getData(True)
data['baaz'] = 'quux'
del data['name']
print p.data

p = Person('bibi', 42, foo='bar')
p.getData()
data['baaz'] = 'quux'
del data['foo']
print p.data

Better to *always* return a copy IMHO.
Mar 14 '07 #3
abcd wrote:
On Mar 14, 7:29 am, "abcd" <codecr...@gmail.comwrote:
>Hi,
I have a dictionary which may contain various keys/values, however,
it will always contain 'name' and 'age' keys.

This dictionary is kept inside a class, such as....

class Person:
def __init__(self, name, age):
self.data = {'name' : name, 'age' : age}

def getData(self, includeNameAge=False):
if includeNameAge: return self.data
tmp = <shallow or deep copy of 'data'>
del tmp['name']
del tmp['age']
return tmp

The getdata method should return the data stored for the
person, however, it should be able to return the data excluding the
'name' and 'age'. Any suggestions on how to best implement this?
Keep in mind this sample code is meant to be an example, I realize
that a person would probably always want the name and age returned.

thanks


I guess one solution might be....

def getData(self, includeNameAge=False):
if includeNameAge: return self.data
return dict(filter(lambda item: item[0] not in ('name', 'age'),
self.data.items()))

any other suggestions, improvements?
You might find

return dict((x,y) for (x, y) in self.data.iteritems()
if x not in ('name', 'age'))

easier to understand. Or you might not ...

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

Mar 14 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Mickel Grönroos | last post by:
Hi! Are there any standard list methods for getting the intersection and difference of two lists? (The union is easy ("list1.extend(list2)"), unless you want it to contain unique values.) ...
9
by: Robin Cull | last post by:
Imagine I have a dict looking something like this: myDict = {"key 1": , "key 2": , "key 3": , "key 4": } That is, a set of keys which have a variable length list of associated values after...
8
by: Hank | last post by:
Hi, I have a CSV file from excel that looks like this (simplified): name,description,type1,type2,name,filename test1,this is a test,0.000,1.000,, test2,another...
15
by: Ron Adam | last post by:
Does anyone have suggestions on how to improve this further? Cheers, Ron_Adam def getobjs(object, dlist=, lvl=0, maxlevel=1): """ Retrieve a list of sub objects from an object. """
181
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ...
1
by: isaphrael | last post by:
I am trying to filter the selections made from a query on a form with the tab control. In general there will be 2 or 3 results for the query, and there are 3 tabs. The tabs have the same name as...
3
by: Brian | last post by:
A quick question here - What can be achieved in IL which is not possible in C# ? o Creation of an ArrayList o Creation of a Dictionary o Creation of a two dimensional array...
5
by: Robocop | last post by:
Is it possible to do something like this syntactically: year = '2008' month = '09' limit = '31' for i in range(1,limit): temp = Table.objects.filter(date = year'-'month'-'i) <----screwed...
9
by: kwerkyone | last post by:
I have two separate but similar databases and each has a split form that acts as the main form used. One of these split forms is able to be filtered from the datasheet portion of the split form using...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.