Pythonic way to create 3d dict

I want to create a dict that can be accessed:

d[id_1][id_2][id_3] = amount

At the moment, I have a huge ugly function:

 def parse_dict(id1,id2,id3,principal, data_dict):
        if data_dict.has_key(id1):
           values = data_dict[id1]
           if values.has_key[id2]
              ..
        else:
            inner_inner_dict = {}
             # and so on

What is the pythonic way to do this?

Notice that I introduce the principal .. but what I want is the sum .. So, if all three keys are there .. add the principal to the previous sum!

thank

+5
source share
5 answers

You might want to use defaultdict:

For instance:

json_dict = defaultdict(lambda: defaultdict(dict))

will create defaultdictfrom defaultdictof dict(I know ... but that's right) to access it, you can simply do:

json_dict['context']['name']['id'] = '42'

without resorting to use if...elsefor initialization.

+15
source
from collections import defaultdict

d = defaultdict(lambda : defaultdict(dict))

d[id_1][id_2][id_3] = amount
+5
source

, ( Autovivification):

>>> class AutoDict(dict):
    def __missing__(self, key):
        x = AutoDict()
        self[key] = x
        return x

>>> d = AutoDict()
>>> d[1][2][3] = 4
>>> d
{1: {2: {3: 4}}}

, defaultdict dict .

Or a simpler version using defaultdict(from the wiki link above):

def auto_dict():
    return defaultdict(auto_dict)
+4
source
>>> from collections import defaultdict
>>> import json

>>> def tree(): return defaultdict(tree)

>>> t = tree()
>>> t['a']['b']['c'] = 'foo'
>>> t['a']['b']['d'] = 'bar'
>>> json.dumps(t)
'{"a": {"b": {"c": "foo", "d": "bar"}}}'
+4
source

Perhaps you need to take a look at multidimensional arrays - for example, in numpy:

http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html

0
source

All Articles