Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python remove keys with the same value on a dictionary

I need to do a not "natural" operation on a dictionary so i wondering what is the best pythonic way to do this.

I need to simplify a dictionary by removing all the keys on it with the same value (keys are differents, values are the same)

For example: Input:

  dict = {key1 : [1,2,3], key2: [1,2,6], key3: [1,2,3]}

expected output:

  {key1 : [1,2,3], key2:[1,2,6]}

I dont care about which key is delete (on the example: key1 or key3)

like image 545
Ariel M Avatar asked Oct 23 '25 20:10

Ariel M


2 Answers

Exchange keys and values; duplicated key-value pairs will be removed as a side effect (because dictionary does not allow duplicated keys). Exchange keys and values again.

>>> d = {'key1': [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}
>>> d2 = {tuple(v): k for k, v in d.items()}  # exchange keys, values
>>> d = {v: list(k) for k, v in d2.items()}   # exchange again
>>> d
{'key2': [1, 2, 6], 'key1': [1, 2, 3]}

NOTE: tuple(v) was used because list is not hashable; cannot be used as key directly.

BTW, don't use dict as a variable name. It will shadow builtin function/type dict.

like image 68
falsetru Avatar answered Oct 25 '25 11:10

falsetru


This solution deletes the keys with same values without creating a new dictionary.

seen = set()
for key in mydict.keys():
    value = tuple(mydict[key])
    if value in seen:
        del mydict[key]
    else:
        seen.add(value) 
like image 29
Ozgur Vatansever Avatar answered Oct 25 '25 10:10

Ozgur Vatansever