将列表值与字典匹配,并在新字典中返回键/值对 [英] Match list values to dict and return key/value pairs in new dict

查看:85
本文介绍了将列表值与字典匹配,并在新字典中返回键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代表字典值的列表.我试图解析字典以查找也在列表中的值,然后从中创建一个仅包含匹配值的新字典:

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}

但是,我回来的只是:

{}

谁能告诉我我要去哪里错了?

Can anyone tell me where I am going wrong?

推荐答案

k表示键,而v

>>> 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}

因此,要实现您想要的目标,您必须执行if v in a.

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

这篇关于将列表值与字典匹配,并在新字典中返回键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆