Quick Filter Dictionary
abcd
codecraig at gmail.com
Wed Mar 14 07:43:18 EDT 2007
On Mar 14, 7:29 am, "abcd" <codecr... at gmail.com> wrote:
> 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?
More information about the Python-list
mailing list