So I have a dictionary with this structure
dict = {
A : [1, 2, 3, 4, 5],
B : [2, 3, 4, 5, 6],
C : [3, 4, 5, 6, 7]
}
I want to end up with only the respective unique elements in each dictionary value
dict = {
A : [1],
B : [],
C : [7]
}
CodePudding user response:
Using collections.Counter
and a couple of comprehensions:
d = {
'A': [1, 2, 3, 4, 5],
'B': [2, 3, 4, 5, 6],
'C': [3, 4, 5, 6, 7]
}
from collections import Counter
counts = Counter(x for lst in d.values() for x in lst)
result = {k: [x for x in lst if counts[x] == 1] for k, lst in d.items()}
CodePudding user response:
For each key, if a value is in one of the other keys as well, remove it (or don't include it).
def unique(val):
count = 0
for _, arr in pairs.items():
for v in arr:
if v == val:
count = count 1
return count == 1
pairs = {
'A' : [1, 2, 3, 4, 5],
'B' : [2, 3, 4, 5, 6],
'C' : [3, 4, 5, 6, 7]
}
result = {}
for key, arr in pairs.items():
result[key] = []
for val in arr:
if unique(val):
result[key].append(val)
print(result) # {'A': [1], 'B': [], 'C': [7]}