Removing dictionary-keys not in a set?

Tim N. van der Leeuw tim.leeuwvander at nl.unisys.com
Mon Apr 18 07:49:06 EDT 2005


Hi,

I'd like to remove keys from a dictionary, which are not found in a
specific set. So it's kind of an intersection-operation.

I can create a new dictionary, or a loop over all keys and test them
for set-membership, but I was wondering if there was a smart way to
express this in 1 or 2 concise statements that I'm not aware of.

So are there smarter ways to get the intersection of dictionary and set
into a dictionary than the following pseudo-code:

# Variation 1
d2 = {}
for key in s: d2[key] = d1[key]

# Variation 2
for key in d.iterkeys(): if key not in s: del d[key]


And if there's no smarter way, then which of these two options would
give best performance?

Cheers,

--Tim




More information about the Python-list mailing list