簡體   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