Tim N. van der Leeuw wrote:
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]

You could try a generator expression:

py> d = {1: 2, 3: 4, 5: 6, 7: 8, 9: 10}
py> s = set([1, 5, 7])
py> dict((k, v) for k, v in d.iteritems() if k in s)
{1: 2, 5: 6, 7: 8}

Note that your variation 2 won't work:

py> for key in d.iterkeys():
...     if key not in s:
...         del d[key]
...
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
RuntimeError: dictionary changed size during iteration

You can make it work using keys() instead of iterkeys():

py> for key in d.keys():
...     if key not in s:
...         del d[key]
...
py> d
{1: 2, 5: 6, 7: 8}

But I think I'd probably lean towards the generator expression...

STeVe
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to