How to make a python dictionary have only unique keys?

Is it possible to create a dictionary in python so that it has unique keys, and if a key is added by mistake that is already in the dictionary, it is rejected. thanks

+7
source share
4 answers

You can always create your own vocabulary.

class UniqueDict(dict): def __setitem__(self, key, value): if key not in self: dict.__setitem__(self, key, value) else: raise KeyError("Key already exists") 
+18
source

Just check your dict before adding an item

 if 'k' not in mydict: mydict.update(myitem) 
+4
source

This is the purpose of setdefault:

 >>> x = {} >>> print x.setdefault.__doc__ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D >>> x.setdefault('a', 5) 5 >>> x {'a': 5} >>> x.setdefault('a', 10) 5 >>> x {'a': 5} 

It also means that you can skip the "if" key in dict: ... else: ... "

 >>> for val in range(10): ... x.setdefault('total', 0) ... x['total']+=val ... 0 0 1 3 6 10 15 21 28 36 >>> x {'a': 5, 'total': 45} 
+1
source

You can create a custom dictionary by getting a dict and overriding __setitem__ to reject items already in the dictionary.

0
source

All Articles