I need to make a two dimensional dictionary in python. e.g. new_dic[1][2] = 5
When I make new_dic = {}
, and try to insert values, I get a <
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'
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]