how to compare list of dict with each key in python?

Viewed 68
list1 = [
    {'A':'a','B':'b','C':'c'},
    {'A':'aa','B':'bb','C':'cc'},
    {'A':'aaa','B':'bbb','C':'ccc'}
    ]

list2 =  [
    {'A':'a','B':'b','C':'c'},
    {'A':'aa','B':'bb','C':'cc'},
    {'A':'aaa','B':'bbb','C':'ccc'}
    ]

I have 2 such list of dict (ex) , I want to compare each key of both lists, means A of dict1 1st list with A of dict1 2nd list , A of dict2 of list1 to A of dict2 of list2 similarly I have to check all the keys, but my expected output is

{'A':True , 'B':True , 'C':True} Means if all the A match with each other from both the dict it will return true and even If one do not match it will written as false

( ex in dict2 of list 1 if value of say 'B' is 'bb' if that do not match with dict2 of list 2 then B will be false if all all other B are matching in other dict

3 Answers

You can get all the keys for all dicts from both lists, and then check the set of values are the same from each list using a dict comprehension.

keys = set(k for d in list1 + list2 for k in d.keys())
d_combined = {k:set(d[k] for d in list1) == set(d[k] for d in list2) for k in keys}

Ouput:

{'A': True, 'C': True, 'B': True}

But if the order of the elements in the two lists is important then this won't be sufficient.

Looping through the keys of dict in both list So, try this code;

Solution 1: (If order of keys is important):

dct = {}
for l1,l2 in zip(list1,list2):
    for k1,k2 in zip(l1.keys(),l2.keys()):
        if k1 == k2:
            if k1 in dct.keys():
                dct[k1] += 1
            else:
                dct[k1] = 1
for key,value in dct.items():
    if value != len(list1):
        dct[key] = False
    else:
        dct[key] = True

Solution 2: (If order of keys is not important):

dct = {}
for l1,l2 in zip(list1,list2):
    for k1 in l1.keys():
        if k1 in l2.keys():
            if k1 in dct.keys():
                dct[k1] += 1
            else:
                dct[k1] = 1
for key,value in dct.items():
    if value != len(list1):
        dct[key] = False
    else:
        dct[key] = True

Hope this Helps...

By using pandas:

import pandas as pd

list1 = [
    {'A':'a','B':'b','C':'c'},
    {'A':'aa','B':'bb','C':'cc'},
    {'A':'aaa','B':'bbb','C':'ccc'}
    ]

list2 =  [
    {'A':'a','B':'b','C':'c'},
    {'A':'aa','B':'bb','C':'cc'},
    {'A':'aaa','B':'bbb','C':'ccc'}
    ]

df1 = pd.DataFrame(list1)
df2 = pd.DataFrame(list1)

output={}
for i in df1.columns:
    output[i] = df1[i].equals(df2[i])

        
print(output)

Output:

{'A': True, 'B': True, 'C': True}
Related