Mdick
Mdick

Reputation: 37

Finding Duplicate Values in a Dictionary

I'm writing a script to find duplicated values in a dictionary. My dictionary duties has an integer key and a list as a value. My task is to make a new dictionary duties_without_duplicates without duplicate values.

duties = { 
    0: ["Submit an assignment","Submit an assignment"],
    1: ["Submit an assignment", "Finish a book review"]
}

duties_without_duplicates = {
    0: ["Submit an assignment"],
    1: ["Submit an assignment", "Finish a book review"]
}

Can anyone help me how to solve this problem?

Upvotes: 0

Views: 110

Answers (2)

ThePyGuy
ThePyGuy

Reputation: 18406

You can use grouby from itertools, and use the keys provided by groupby iterator for the unique values in the list, and you can implement a dictionary comprehension to achieve that:

>>> from itertools import groupby
>>> {key:[k for k,v in groupby(values)] for key,values in duties.items()}

{0: ['Submit an assignment'], 1: ['Submit an assignment', 'Finish a book review']}

As I've mentioned in comments as well, above solution will work only if the values list is sorted, otherwise, you can use following method:

result = {}
for key,values in duties.items():
    temp = []
    for v in values:
        if v not in temp:
            temp.append(v)
    result[key]=temp

# result: 
{0: ['Submit an assignment'], 1: ['Submit an assignment', 'Finish a book review']}

Upvotes: 1

Mortz
Mortz

Reputation: 4879

If the order of items in your lists is not important, you can simply pass the lists to a set constructor -

duties = { 
    0: ["Submit an assignment","Submit an assignment"],
    1: ["Submit an assignment", "Finish a book review"]
}
duties_without_duplicates = {k: list(set(v)) for k, v in duties.items()}

Output

{0: ['Submit an assignment'],
 1: ['Submit an assignment', 'Finish a book review']}

Upvotes: 1

Related Questions