Compare lists in the same dictionary of lists
You could use set:
d = {'a':[1,2,3,4,5], 'b':[2,3,4,6]}
print(list(set(d['a'])-set(d['b'])))
print(list(set(d['b'])-set(d['a'])))
print(list(set(d['b'])&set(d['a'])))
result:
[1, 5]
[6]
[2, 3, 4]
you can do that by utilising python
inbuilt functions like union
, difference
, intersection
.
Note: These are for sets
,
you can convert a list
to set
by
1stset = set(a)
example:
print(1stset.difference(2ndset))
print(1stset.intersection(2ndset))
print(1stset.union(2ndset))
you can refer the following links for more information
https://www.geeksforgeeks.org/python-intersection-two-lists/
https://www.geeksforgeeks.org/python-union-two-lists/
https://www.geeksforgeeks.org/python-difference-two-lists/
A solution with list comprehension would be:
dictionary = {'a':[1,2,3,4,5], 'b':[2,3,4,6]}
only_in_a = [x for x in dictionary['a'] if not x in dictionary['b']]
only_in_b = [x for x in dictionary['b'] if not x in dictionary['a']]
in_both = [x for x in dictionary['a'] if x in dictionary['b']]
Note that this is not especially wise in terms of complexity, for larger lists.