Home > Blockchain >  How to remove duplicate values from a list which are the values in the dictionary?
How to remove duplicate values from a list which are the values in the dictionary?

Time:07-10

I made a dictionary subclass that will store duplicated values in lists under the same key automatically from reference to

Make a dictionary with duplicate keys in Python

class Dictlist(dict):
    def __setitem__(self, key, value):
        try:
            self[key]
        except KeyError:
            super(Dictlist, self).__setitem__(key, [])
        self[key].append(value)

d = Dictlist()

d['test'] = 1
d['test'] = 2
d['test'] = 1
d['test'] = 1

print(d)
{'test' : [1,2,1,1]}
for k,v in d.items():
    d[k] = list(set(v))

print(d)
{'test': [1, 2, 1, 1, [1, 2]]}

In this case, the new list is being added to the values list. I just want [1,2] in the values.

CodePudding user response:

You've overriden __setitem__, so the line d[k] = list(set(v)) will call the override and append to the list. In order to set the key directly, you need to bypass the override and access the method in dict.

One way to do this would be to provide a method in Dictlist. For instance:

def set_item(self, key, value):
    super().__setitem__(key, value)

and then call d.set_item(k, list(set(v))).

If this uniquification is the only operation you need to perform on the dictionary that uses this bypass, you could put all the logic in one method of Dictlist:

def uniquify(self):
    for key in self.keys():
        super().__setitem__(key, list(set(self[key])))

If for whatever reason you can't modify Dictlist, you can bypass from outside the class as follows:

dict.__setitem__(d, k, list(set(v)))
  • Related