2016-12-05 148 views
0

我有一個字典列表,並希望找到匹配的列表元素(元素是一個完整的字典)。不知道如何在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

一些能幫助一個與這個問題一個很好的解決方案呢?

+2

'如果dict_to_match in list_of_dict:' –

+0

如果你只是想知道如何比較2個字母:http://stackoverflow.com/questions/4527942/comparing-two-dictionaries-in-python – roymustang86

回答

2

從比較的整數或字符串並非如此不同:

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和建議。

+1

是否有某種原因不是使用'in'? –

+0

@PatrickHaugh沒有.. – Wentao

+0

@ShadowRanger更新。 – Wentao

0

使用循環和等號操作者:

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 
0
if dict_to_match in list_of_dict: 
    print "a match found" 
-1

的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] 
+1

如果您需要'lambda'來使用'filter',請不要使用'filter'。它會比等效的列表理解或生成器表達式(並且listcomp/genexpr在Py2和Py3上具有相同的語義)慢,省略了'lambda':'[d for list_of_dict if d == dict_to_match]' 。當然,在這種情況下,你只需要其中的一個,而你實際上並不需要返回它,所以它無論如何都是毫無意義的。 – ShadowRanger

0
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 

我已經測試了這個代碼,它的工作原理,我希望它可以幫助你。

相關問題