Home > Blockchain >  Check if dictionaries match in a list of dicts & if they do, add value True or False
Check if dictionaries match in a list of dicts & if they do, add value True or False

Time:03-11

I would like to compare two list of dictionaries, if the dictionary matches then add a key/value True to the second list of dictionaries; and if they don't match add a key/value False to the second list of dictionaries.

Current code:

list_dict1 = [{'animal': 'Dog', 'age': '3'}, {'animal':'Horse', 'age': '6'}]
list_dict2 = [{'animal': 'Dog', 'age': '3'}, {'animal':'Horse', 'age': '8'}]

for d1 in list_dict1:
    for d2 in list_dict2:
        if d1 == d2:
            d2['match'] = True
        else:
            d2['match'] = False

Current output:

list_dict2 = [{'animal': 'Dog', 'age': '3', 'match': False},
 {'animal': 'Horse', 'age': '8', 'match': False}]

Desired output:

list_dict2 = [{'animal': 'Dog', 'age': '3', 'match': True},
 {'animal': 'Horse', 'age': '8', 'match': False}]

I'm assuming that the reason why this does not work, is because at each iteration the list_dict2 changes, meaning that there is no match further down the loops because I am adding a new value. Any ideas how I can proceed ?

CodePudding user response:

The problem with your solution is that you override the results again.

I would just go over the second list and check if each item is in the first list like this:

for d1 in list_dict2:
    if d1 in list_dict1:
        d1['match'] = True
    else:
        d1['match'] = False

print(list_dict2)

Output:

[{'animal': 'Dog', 'age': '3', 'match': True},
 {'animal': 'Horse', 'age': '8', 'match': False}]
  • Related