繁体   English   中英

匹配字典python列表中的整个元素

[英]match entire element in a list of dictionaries python

我有一个字典列表,想要找到此列表元素的匹配项(元素是整个字典)。 不确定如何在Python中执行此操作。

这是我需要的:

list_of_dict = [ {a : 2, b : 3, c : 5}, {a : 4, b : 5, c : 5}, {a : 3, b : 4, c : 4} ]

dict_to_match = {a : 4, b : 5, c : 5}

因此,在上面的输入中, dict_to_match应该与列表list_of_dict中的第二个元素匹配

有人可以为这个问题提供一个好的解决方案吗?

与比较整数或字符串没什么不同:

list_of_dict = [ {'a' : 2, 'b' : 3, 'c' : 5}, {'a' : 4, 'b' : 5, 'c' : 5}, {'a' : 3, 'b' : 4, 'c' : 4} ]

dict_to_match = {'a' : 4, 'b' : 5, 'c' : 5}

if dict_to_match in list_of_dict:
    print("a match found at index", list_of_dict.index(dict_to_match))
else:
    print("not match found")

Patrick HaughShadowRanger建议。

使用循环和equals运算符:

list_of_dict = [ {a : 2, b : 3, c : 5}, {a : 4, b : 5, c : 5}, {a : 3, b : 4, c : 4} ]
dict_to_match = {a : 4, b : 5, c : 5}
for i, d in enumerate(list_of_dict):
    if d == dict_to_match:
        print 'matching element at position %d' % i
if dict_to_match in list_of_dict:
    print "a match found"
list_of_dict = [ {'a' : 2, 'b' : 3, 'c' : 5}, {'a' : 4, 'b' : 5, 'c' : 5}, {'a' : 3, 'b' : 4, 'c' : 4} ]

dict_to_match = {'a' : 4, 'b' : 5, 'c' : 5}

for each in list_of_dict:
   if each == dict_to_match:
     print each, dict_to_match 

我已经测试了此代码,并且可以正常工作,希望对您有所帮助。

Python <3:

filter(lambda x: x == dict_to_match, list_of_dict)[0]

Python 3:

list(filter(lambda x: x == dict_to_match, list_of_dict))[0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM