1
votes

I have the dictionary values as follows in python:

X = {7: [0, 2], 9: [2, 3], 11: [1, 10], 13: [10, 4], 15: [8, 12], 16: [12, 14, 2], 20: [21, 22] , 32:[13]}

Now I want to take the key values in a list, which has at least one value common in the dictionary.

example: list of common keys with at least one common value: (7, 9, 16), (11, 13), (15, 16)

also
group of keys that does not share any common value with others.

Example: (20,32)

What will be the best way to do this?

1

1 Answers

1
votes

You can first build an inverted dict matching each possible value to the list of keys that contain it. The rest is then fairly easy:

from collections import defaultdict

X= {7: [0, 2], 9: [2, 3], 11: [1, 10], 13: [10, 4], 15: [8, 12], 16: [12, 14,2], 20:[21,22] , 32:[13] }

out = defaultdict(list)
for key, values in X.items():
    for val in values:
        out[val].append(key)
        
        
# You get defaultdict(<class 'list'>, {0: [7], 2: [7, 9, 16], 3: [9], 1: [11], 10: [11, 13], 
#  4: [13], 8: [15], 12: [15, 16], 14: [16], 21: [20], 22: [20], 13: [32]})

common = {key:values for key, values in out.items() if len(values) > 1}
print(common)
# {2: [7, 9, 16], 10: [11, 13], 12: [15, 16]}

# if you don't care about the keys: 
print(list(common.values()))
# [[7, 9, 16], [11, 13], [15, 16]]

uniques = set(X) - set(k for keys in common.values() for k in keys)

print(uniques)
# {20, 32}