0

I have a list of dictionaries and want to find a match for the element of this list(element being an entire dictionary). Not sure how to do this in Python.

Here is what I need:

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}

so with above input the dict_to_match should match the second element in list list_of_dict

Can some one help with a good solution for this problem?

pynew
  • 31
  • 1

5 Answers5

2

Not so different from comparing an integer or a string:

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")

Suggested by Patrick Haugh and ShadowRanger.

Community
  • 1
  • 1
Rahn
  • 4,787
  • 4
  • 31
  • 57
0

Using a loop and the equals operator:

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
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
0
if dict_to_match in list_of_dict:
    print "a match found"
khelili miliana
  • 3,730
  • 2
  • 15
  • 28
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 

I have tested this code and it works, I hope it helps you.

-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]
gipsy
  • 3,859
  • 1
  • 13
  • 21
  • 1
    If you need a `lambda` to use `filter`, don't use `filter`. It's going to be slower than the equivalent list comprehension or generator expression (and the listcomp/genexpr will have identical semantics on both Py2 and Py3) that omits the `lambda`: `[d for d in list_of_dict if d == dict_to_match]`. Of course, in this case, you only want one of them, and you don't actually need to return it, so it's sort of pointless regardless. – ShadowRanger Dec 05 '16 at 14:19