Selecting dictionary items by key efficiently in Python

Posted by user248237 on Stack Overflow See other posts from Stack Overflow or by user248237
Published on 2010-06-09T22:03:49Z Indexed on 2010/06/09 22:12 UTC
Read the original article Hit count: 120

Filed under:
|
|

suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list?

for example:

# a dictionary mapping strings to stuff
mydict = {'quux': ...,
          'bar': ...,
          'foo': ...}

# list of keys to be selected from mydict
keys_to_select = ['foo', 'bar', ...]

The way I came up with is:

filtered_mydict = [mydict[k] for k in mydict.keys() \ 
                   if k in keys_to_select]

but I think this is highly inefficient because: (1) it requires enumerating the keys with keys(), (2) it requires looking up k in keys_to_select each time. at least one of these can be avoided, I would think. any ideas? I can use scipy/numpy too if needed.

© Stack Overflow or respective owner

Related posts about python

Related posts about numpy