Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading