Search code examples
pythonpython-3.xdictionarynested

How to add multiple nested dictionaries at once?


I have a method which requires being able to add multiple nested dictionaries at once.

For example:

mydict = {}
mydict['subdict']['subdict2'] = {'this': 'is what i want'}

How can I do this?


Solution

  • from collections import defaultdict
    mydict = defaultdict(dict)
    mydict['subdict']['subdict2'] = {'this': 'is what i want'}