2016-12-05 85 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 

我已经测试了这个代码,它的工作原理,我希望它可以帮助你。

相关问题