Given the following dictionary and set:
d = {1 : a, 2 : b, 3 : c, 4 : d, 5 : e }
s = set([1, 4])
I was wondering if it is possible to remove all dictionary entries that are not contained in the set (i.e. 2,3,5). I am aware that i can achieve this by iterating over the dictionary and check each key but since i'm new to Python and came across many "shortcuts" so far I was wondering if there exists one for this particular problem.
d = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e' }
s = set([1, 4])
Since you should not modify a dictionary while itering over it, you have two possibilities to create a new dictionary.
One is to create a new dictionary from the old one filtering values out:
d2 = dict((k,v) for k,v in d.iteritems() if k in s)
The second one is to extract the keys, intersect them with the s
-set and use them to build a new dictionary:
d2 = dict((k, d[k]) for k in set(d) & s)
The third one is to remove the elements directly from d
:
for k in set(d) - s:
del d[k]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With