将列表与Dict比较-如果值与列表匹配,则返回键 [英] Comparing List against Dict - return key if value matches list

查看:87
本文介绍了将列表与Dict比较-如果值与列表匹配,则返回键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Python 3.6

This is Python 3.6

我需要比较列表和字典的帮助,如果匹配,我需要返回字典键。

I need help comparing a list against a dictionary and if there is match I need to return the dictionaries key.

champ_ids = [0, 36, 85]

champ_dict = {Bob : 0, Carly: 36, Freddy : 85, Megan : 14, Dilbert : 69}

for item in champ_dict.items() and champ_ids:
    print(item)

这会打印所有匹配的数字,因此在这种情况下 0、36、85 完美。如果在两个地方都找到了这些值,该如何返回 Bob,Carly,Freddy (这些键),而不是返回匹配的值

That prints all the matching numbers so in this case 0, 36, 85 which is perfect. How do I make it return Bob, Carly, Freddy (the keys) if those values are found in both places, instead of returning the values that match

推荐答案

请注意,问题中的这段代码不是 所做的:

Notice that this code in the question is not doing what you imagine:

for item in champ_dict.items() and champ_ids:

上面的不是检查项目是否在字典和列表中(这不是的方式)在中使用Python!)。只是遍历 champ_ids 列表,仅此而已。改试试这个方法:

The above does not check if the item is in both the dictionary and the list (that's not how in, and work in Python!). It's simply iterating over the champ_ids list, and nothing more. Try this instead:

champ_ids  = [0, 36, 85]
champ_dict = {'Bob' : 0, 'Carly': 36, 'Freddy' : 85, 'Megan' : 14, 'Dilbert' : 69}
[k for k, v in champ_dict.items() if v in champ_ids]

上面将比较字典中的每个,如果它们出现在列表中将相应的 key 添加到输出列表中。例如,这是问题中测试数据的输出:

The above will compare each value in the dictionary and if it's present in the list it'll add the corresponding key to an output list. For instance, this is the output for the test data in the question:

['Freddy', 'Bob', 'Carly']

现在您可以根据需要使用它了, print()它。

Now you can use it as needed, print() it if you want.

这篇关于将列表与Dict比较-如果值与列表匹配,则返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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