Reputation: 7464
I want to copy selected elements between dictionaries. Is there a better/more efficient way than this:
dict1 = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
list = ['a', 'd']
dict2 = { k : dict1[k] for k in dict1 if k in list }
?
Upvotes: 0
Views: 312
Reputation: 304255
There's the functional way
>>> dict1 = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
>>> lst = ['a', 'd']
>>> dict(zip(lst, map(dict1.get, lst)))
{'a': 1, 'd': 4}
or
>>> from operator import itemgetter
>>> dict(zip(lst, itemgetter(*lst)(dict1)))
{'a': 1, 'd': 4}
But they are ~3 times slower than the dict comprehension :)
Upvotes: 1
Reputation: 59984
Yes, use dict.get()
and iterate through the list of keys instead of the dictionary.
>>> {k:dict1.get(k) for k in list1}
{'a': 1, 'd': 4}
Note, you shouldn't override the built-in type list
.
This is especially helpful as if k
isn't a key in dict1, then None
is returned.
Upvotes: 4