Syntax for extracting multiple items from a dictionary

Bengt Richter bokr at oz.net
Tue Nov 30 16:54:46 EST 2004


On Tue, 30 Nov 2004 15:20:19 +0100, Stefan Behnel <behnel_ml at gkec.informatik.tu-darmstadt.de> wrote:

>
>
>shark schrieb:
>> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
>> "Alaska"}
>> cols = ("city", "state")
>> 
>> Is there a best-practices way to ask for an object containing only the keys
>> named in cols out of row? In other words, to get this:
>> {"city" : "Hoboken", "state" : "Alaska"}
>
>Untested:
>
>dict( (key,value) for (key,value) in row.iteritems() if key in cols )

If there's an overall why for doing it at all, why not just iterate through
keys of interest? I.e., (untested)

 dict( (key, row[key]) for key in cols )

>
>Works in Py2.4
>
>Stefan

Regards,
Bengt Richter



More information about the Python-list mailing list