user248237
user248237

Reputation:

Selecting dictionary items by key efficiently in Python

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.

Upvotes: 6

Views: 5721

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882251

dict((k, mydict[k]) for k in keys_to_select)

if you know all the keys to select are also keys in mydict; if that's not the case,

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

Upvotes: 15

Related Questions