Aug-14-2018, 03:50 PM
you can use dict.setdefault() method
d = {} d.setdefault('key1', {})['key2'] = 'foo' print(d) d.setdefault('key1', {})['key3'] = 'bar' print(d)
Output:{'key1': {'key2': 'foo'}}
{'key1': {'key3': 'bar', 'key2': 'foo'}}
another option is to use defaultdict from collectionsfrom collections import defaultdict d = defaultdict(dict) d['key1']['key2'] = 'foo' print(d) d['key1']['key3'] = 'bar' print(d)
Output:defaultdict(<class 'dict'>, {'key1': {'key2': 'foo'}})
defaultdict(<class 'dict'>, {'key1': {'key2': 'foo', 'key3': 'bar'}})
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs