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

2024-04-24 16:14:17 发布

您现在位置: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中的第二个元素

有人能帮忙解决这个问题吗?你知道吗


Tags: ofto元素列表字典matchdictlist
3条回答

使用循环和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}

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建议。你知道吗

相关问题 更多 >