Home > Software design >  Find equal values among multiple collections within dictionary
Find equal values among multiple collections within dictionary

Time:05-31

I have a dictionary:

d = {"key1": [a,b,c], "key2": [b,c,d,e], "key3": [a,e]}

I need to compare the values to get a result as follows:

"Key1 and Key2" have 2 equal values # b, c
"Key1 and Key3" have 1 equal values # a
"Key2 and Key3" have 1 equal values # e

Update, I tried this:

for v in enumerate(d):
    for k in d.keys():
        if v[1] != k:
           print("{} compare with{}".format(v[1], d[k]))

But it's not the solution

CodePudding user response:

You can use itertools.combinations to get key combinations, and then use & set operator to get intersections.

from itertools import combinations

dic = {"key1": ['a','b','c'], "key2": ['b','c','d','e'], "key3": ['a','e']}

for (k1, l1), (k2, l2) in combinations(dic.items(), r=2):
    common = set(l1) & set(l2)
    print(f"{k1} and {k2} have {len(common)} equal values: {', '.join(common)}")

# key1 and key2 have 2 equal values: b, c
# key1 and key3 have 1 equal values: a
# key2 and key3 have 1 equal values: e

If for some reason you are hesitant to use itertools:

for i, k1 in enumerate(dic):
    for k2 in list(dic)[:i]:
        common = set(dic[k1]) & set(dic[k2])
        print(f"{k1} and {k2} have {len(common)} equal values: {', '.join(common)}")
  • Related