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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.