Syntax for extracting multiple items from a dictionary

Roy Smith roy at panix.com
Tue Nov 30 09:11:46 EST 2004


In article <TuednaLvv_626THcRVn-hA at rcn.net>, "shark" <no at spam.none> 
wrote:

> 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"}
> 
> Thanks,
> 
> shark

Just out of curiosity, why would you want to do that?  Are you trying to 
save on memory to store a lot of these things?  If so, I suspect you'd 
do even better (a few bytes per object) to store tuples of just the 
values, i.e. ("Hoboken", "Alaska"), and unpack them as you need them.

But, to answer your question, I don't know of any standard way to do 
what you want.  It's easy enough to write (a production version would 
probably want to catch KeyError's inside the for loop):

def getDictionarySlice (row, cols):
   slice = {}
   for key in cols:
      slice[key] = row[key]
   return slice

This won't work, but it would be kind of cool if it did:

def getOmnicientDictionarySlice (row, cols):
   for key not in cols:
      del row[key]

Hmmm.  Maybe there's an April Fools PEP in there somewhere :-)  
Actually, you could do:

def deleteUnwantedKeysInPlace (row, cols):
   for key in row.keys():
      if key not in cols:
         del row[key]



More information about the Python-list mailing list