1

I have a list that represents the values of a dictionary. I am trying to parse the dictionary looking for values that are also in my list and creating a new dictionary from this that contains only the matched values:

a = [1, 2, 3]
b = {"aye":1, "bee":2, "cee":3, "dee":4, "eee":5}

new_dict = dict((k, v) for k, v in b.iteritems() if k in a)
print new_dict

My desired output should look like this:

new_dict = {"aye":1, "bee":2, "cee":3}

However, all I am getting back is:

{}

Can anyone tell me where I am going wrong?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
gdogg371
  • 3,879
  • 14
  • 63
  • 107
  • 3
    Shouldn't it be `if v in a`? – vaultah Feb 11 '15 at 19:15
  • 2
    `dict((k, v) for k, v in b.iteritems() if k in a)` is Python 2.6 syntax. Unless you happen to be using that old version, the modern solution is to use a dictionary comprehension: `{k:v for k, v in b.iteritems() if k in a}`. –  Feb 11 '15 at 19:19
  • If performance is important to you, `a` should be a `set`. – Akavall Feb 11 '15 at 20:05

1 Answers1

4

k represents the keys and v the values

>>> a = [1, 2, 3]
>>> b = {"aye":1, "bee":2, "cee":3, "dee":4, "eee":5}
>>> new_dict = dict((k, v) for k, v in b.iteritems() if v in a)
>>> print new_dict
{'aye': 1, 'cee': 3, 'bee': 2}

So therefore to achieve what you want, you have to do if v in a instead.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140