Automatically add key to Python dict

I want to automatically add keys to the Python dictionary if they do not already exist. For instance,

a = "a" b = "b" c = "c" dict = {} dict[a][b] = c # doesn't work because dict[a] doesn't exist 

How to automatically create keys if they do not exist?

+4
source share
2 answers

Use collections.defaultdict :

 def recursively_default_dict(): return collections.defaultdict(recursively_default_dict) my_dict = recursively_default_dict() my_dict['a']['b'] = 'c' 
+23
source
 from collections import defaultdict d = defaultdict(dict) d['a']['b'] = 'c' 

Also, be careful when using dict - it matters in python: https://docs.python.org/2/library/stdtypes.html#dict

0
source

Source: https://habr.com/ru/post/1443146/


All Articles