Comparing values in lists of a dictionary in Python

67 Views Asked by At

I'm a beginner learning to use Python and I have a problem with comparing values in dictionary lists. In the example dictionary below, I would like to have a dictionary that is the result of the comparison of the elements of the list in the dictionary, that returns a dictionary in which inside are unique elements of that list, therefore not present in any other list. I want a dictionary that has only unique value in each list respect the others.

dict_test = {'hello': ['a', 'b', 'c', 'k', 'g', 'x'],
  'bye': ['g', 'a', 'c', 'j'],
  'aloa': ['b', 'h', 'a', 'k']}

I try this for loop:

dict_result = {}

for k1, v1 in dict_test.items ():
     for k2, v2 in dict_test.items ():
         if k1!= k2:
             if v1 != v2:
                 list_test = []
                 list_test.append (v1)
                 dict_result [k1] = list_test

But the output is this:

Output:{'hello': [['a', 'b', 'c', 'k', 'g', 'x']],
 'bye': [['g', 'a', 'c', 'j']],
 'aloa': [['b', 'h', 'a', 'k']]}

Instead, the Expected Output is this:

Output: { 'hello': ['x'], ''bye':['j'], 'aloa': ['h'] }
1

There are 1 best solutions below

0
On

You can use the counter first to count the number specific value that exists. Then keep counter value 1 to the perspective dictionary key

from collections import Counter
dict_test = {'hello': ['a', 'b', 'c', 'k', 'g', 'x'],
             'bye': ['g', 'a', 'c', 'j'],
             'aloa': ['b', 'h', 'a', 'k']}

c = Counter(x for xs in dict_test.values() for x in xs)
update_d = {k: [v for v in vs if c[v] == 1] for k, vs in dict_test.items()}
print(update_d)

Output

{'hello': ['x'], 'bye': ['j'], 'aloa': ['h']}