Python – comparing values in the same dictionary
Python – comparing values in the same dictionary
Not as elegant as using Counter
, but does remove duplicates without the use of modules:
d = {Trump: [MAGA, FollowTheMoney],
Clinton: [dems, Clinton],
Stein: [FollowTheMoney, Atlanta]}
dupvals = [item for sublist in d.values() for item in sublist] # get all values from all keys into a list
dups = [] # list to hold duplicates
for i in dupvals:
if dupvals.count(i) > 1:
dups.append(i)
dupvals = set(dups) # keep only one item for each duplicated item
new_d = {}
for key,values in d.items():
for value in values:
if not value in dupvals:
new_d.setdefault(key, []).append(value)
print new_d # {Clinton: [dems, Clinton], Trump: [MAGA], Stein: [Atlanta]}
You can use Counter
to tally how many times each value appears in d
.
d = {Trump: [MAGA, FollowTheMoney],
Clinton: [dems, Clinton],
Stein: [FollowTheMoney, Atlanta]}
from collections import Counter
c = Counter(x for xs in d.values() for x in xs)
In this example, the value of c
is
Counter({Atlanta: 1,
Clinton: 1,
FollowTheMoney: 2,
MAGA: 1,
dems: 1})
Then choose values for which the count is exactly 1.
update_d = {k: [v for v in vs if c[v] == 1] for k, vs in d.items()}