Syntax for extracting multiple items from a dictionary

Stefan Behnel behnel_ml at gkec.informatik.tu-darmstadt.de
Tue Nov 30 15:20:19 CET 2004



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 )

Works in Py2.4

Stefan



More information about the Python-list mailing list