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:
mydict = {'quux': ...,
'bar': ...,
'foo': ...}
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.
source
share