Declaring a multi dimensional dictionary in python

Solution 1:

A multi-dimensional dictionary is simply a dictionary where the values are themselves also dictionaries, creating a nested structure:

new_dic = {}
new_dic[1] = {}
new_dic[1][2] = 5

You'd have to detect that you already created new_dic[1] each time, though, to not accidentally wipe that nested object for additional keys under new_dic[1].

You can simplify creating nested dictionaries using various techniques; using dict.setdefault() for example:

new_dic.setdefault(1, {})[2] = 5

dict.setdefault() will only set a key to a default value if the key is still missing, saving you from having to test this each time.

Simpler still is using the collections.defaultdict() type to create nested dictionaries automatically:

from collections import defaultdict

new_dic = defaultdict(dict)
new_dic[1][2] = 5

defaultdict is just a subclass of the standard dict type here; every time you try and access a key that doesn't yet exist in the mapping, a factory function is called to create a new value. Here that's the dict() callable, which produces an empty dictionary when called.

Demo:

>>> new_dic_plain = {}
>>> new_dic_plain[1] = {}
>>> new_dic_plain[1][2] = 5
>>> new_dic_plain
{1: {2: 5}}
>>> new_dic_setdefault = {}
>>> new_dic_setdefault.setdefault(1, {})[2] = 5
>>> new_dic_setdefault
{1: {2: 5}}
>>> from collections import defaultdict
>>> new_dic_defaultdict = defaultdict(dict)
>>> new_dic_defaultdict[1][2] = 5
>>> new_dic_defaultdict
defaultdict(<type 'dict'>, {1: {2: 5}})

Solution 2:

Check it out:

def nested_dict(n, type):
    if n == 1:
        return defaultdict(type)
    else:
        return defaultdict(lambda: nested_dict(n-1, type))

And then:

new_dict = nested_dict(2, float)

Now you can:

new_dict['key1']['key2'] += 5

You can create as many dimensions as you want, having the target type of your choice:

new_dict = nested_dict(3, list)
new_dict['a']['b']['c'].append(5)

Result will be:

new_dict['a']['b']['c'] = [5]

Solution 3:

Simply, you can use defaultdict

from collections import defaultdict
new_dic = defaultdict(dict)
new_dic[1][2]=5
>>>new_dic
defaultdict(<type 'dict'>, {1: {2: 5}})

Solution 4:

One simple way is to just use tuples as keys to a regular dictionary. So your example becomes this:

new_dic[(1, 2)] = 5

The downside is that all usages have to be with this slightly awkward convention, but if that's OK, this is all you need.

Solution 5:

u can try this, it is even easier if it is string

new_dic = {}
a = 1
new_dic[a] = {}
b = 2
new_dic[a][b] = {}
c = 5
new_dic[a][b]={c}

type

new_dic[a][b]
>>>'5'

For string

new_dic = {}
a = "cat"
new_dic[a] = {}
b = "dog"
new_dic[a][b] = {}
c = 5
new_dic[a][b] = {c}

type

new_dic["cat"]["dog"]
>>>'5'