Andre
Andre

Reputation: 1661

Python How to find duplicate values in Dictionary

Okay I was wondering how I can find duplicate values for a single key in a dictionary.

so I have

import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 1), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k, v in s:
    d[k].append(v)

Output:

defaultdict(<class 'list'>, {'blue': [2, 4], 'yellow': [1, 1], 'red': [1]})

As you can see "Yellow" has duplicate values.

I was wondering, what is the best pythonic way of finding out if there are duplicate values within a key in the dictionary. And after finding them, removing them from the dictionary.

Upvotes: 4

Views: 14898

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180550

You can check before you append:

d = collections.defaultdict(list)
for k, v in s:
    if v not in d[k]: # if value not in list already
        d[k].append(v)

Or use a set to store the values:

d = collections.defaultdict(set)
for k, v in s:
    d[k].add(v) # sets don't have duplicates so we don't need a check here

If you don't want the defaultdict(<class 'list'> output just make d a normal dict with dict(d) or use dict.setdefault using a normal dict,

d = {}
for k, v in s:
    d.setdefault(k,set())
    d[k].add(v)

Upvotes: 4

Related Questions