Home > other >  Compare and eliminate repeating values in the dictionary
Compare and eliminate repeating values in the dictionary

Time:01-09

I have a dictionary as follows:

dict = {'alpha1': ['a', 'b', 'c', 'd', 'e', 'f'], 'alpha2': ['e', 'f', 'g'], 'alpha3': ['j', 'k', 'l', 'm'], 'alpha4': ['h', 'i', 'j', 'k']}

Is it possible to compare the values in the dictionary to ensure that each value appears only one time. I need to eliminate the repeating values so that I can have a dictionary like this:

dict = {'alpha1': ['a', 'b', 'c', 'd', 'e', 'f'], 'alpha2': ['g'], 'alpha3': ['j', 'k', 'l', 'm'], 'alpha4': ['h', 'i']}

I am trying the following:

result = {}
for key, value in dict.items():
    if value not in result.values():
        result[key] = value
print(result)

This is returning the same original dictionary to me. I am quite new to python so any help will be appreciated.

CodePudding user response:

You need to loop over the list elements, and test each string to see if it has been added to any of the lists.

You can use a set to keep all the strings that have been added.

result = {}
seen = set()

for key, value in dict.items():
    for string in value:
        if string not in seen:
            seen.add(string)
            result.setdefault(key, []).append(string)

print(result)

BTW, don't use dict as a variable name. It's already a built-in type.

  • Related