saurabh daund
saurabh daund

Reputation: 1

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

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

Upvotes: 0

Views: 78

Answers (3)

Shahab Rahnama
Shahab Rahnama

Reputation: 1012

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}

Upvotes: 0

Sachin Kohli
Sachin Kohli

Reputation: 1986

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...

Upvotes: 0

bn_ln
bn_ln

Reputation: 1683

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.

Upvotes: 1

Related Questions