Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this:
mydict[key][subkey][subkey2]="value"
without having to check that mydict[key] etc. are actually set to be a dict, e.g. using
if not key in mydict: mydict[key]={}
The creation of subdictionaries should happen on the fly. What is the most elegant way to allow something equivalent - maybe using decorators on the standard <type 'dict'>
?
[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.
The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.
class D(dict):
def __missing__(self, key):
self[key] = D()
return self[key]
d = D()
d['a']['b']['c'] = 3
You could use a tuple as the key for the dict and then you don't have to worry about subdictionaries at all:
mydict[(key,subkey,subkey2)] = "value"
Alternatively, if you really need to have subdictionaries for some reason you could use collections.defaultdict
.
For two levels this is straightforward:
>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d['key']['subkey'] = 'value'
>>> d['key']['subkey']
'value'
For three it's slightly more complex:
>>> d = defaultdict(lambda: defaultdict(dict))
>>> d['key']['subkey']['subkey2'] = 'value'
>>> d['key']['subkey']['subkey2']
'value'
Four and more levels are left as an exercise for the reader. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With