且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将列表与Dict比较-如果值与列表匹配,则返回键

更新时间:2022-06-25 16:49:58

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

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.