字典键与列表匹配;获取键/值对 [英] Dictionary keys match on list; get key/value pair

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

问题描述

在python中...我有一个元素列表 my_list,以及一个字典 my_dict,其中某些键在 my_list中匹配。

In python... I have a list of elements 'my_list', and a dictionary 'my_dict' where some keys match in 'my_list'.

我会喜欢搜索字典并检索与 my_list元素匹配的键的键/值对。

I would like to search the dictionary and retrieve key/value pairs for the keys matching the 'my_list' elements.

我尝试了这个...

    if any(x in my_dict for x in my_list):
          print set(my_list)&set(my_dict)

但是它没有用。

推荐答案

(我将 list重命名为 my_list dict my_dict 以避免与类型名称冲突。)

(I renamed list to my_list and dict to my_dict to avoid the conflict with the type names.)

为了获得更好的性能,您应该遍历列表并检查字典中的成员资格:

For better performance, you should iterate over the list and check for membership in the dictionary:

for k in my_list:
    if k in my_dict:
        print k, my_dict[k]

如果要根据这些键值对创建新字典,请使用

If you want to create a new dictionary from these key-value pairs, use

new_dict = {k: my_dict[k] for k in my_list if k in my_dict}

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

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