Choosing dictionary entries with a key efficiently in Python

Suppose I have a dictionary whose keys are strings. How can I effectively make a new dictionary from one that contains only the keys that are present in some list?

eg:

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

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

What 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 very inefficient, because: (1) it requires enumerating keys with the keys (), (2) it requires finding k in keys_to_select every time. I would think at least one of them can be avoided. any ideas? If necessary, I can use scipy / numpy.

+5
source share
1 answer
dict((k, mydict[k]) for k in keys_to_select)

, mydict; ,

dict((k, mydict[k]) for k in keys_to_select if k in mydict)
+15

All Articles