Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating dictionary keys on the fly [duplicate]

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'>?

like image 322
relet Avatar asked Aug 04 '10 11:08

relet


People also ask

Do dictionaries allow duplicate keys?

[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<> .

Can a dictionary have multiple identical keys?

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.

How can you copy the entire dictionary to a new 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.


2 Answers

class D(dict):
    def __missing__(self, key):
        self[key] = D()
        return self[key]

d = D()
d['a']['b']['c'] = 3
like image 75
John La Rooy Avatar answered Sep 27 '22 20:09

John La Rooy


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. :-)

like image 20
Dave Webb Avatar answered Sep 27 '22 19:09

Dave Webb