You can use collections.defaultdict for a nested dictionary, where you define an initial value of a dictionary
from collections import defaultdict
#Use the initial value as a dictionary
dct = defaultdict(dict)
dct['a']['b'] = 'c'
dct['d']['e'] = 'f'
print(dct)
The output will be
defaultdict(<class 'dict'>, {'a': {'b': 'c'}, 'd': {'e': 'f'}})
Answer from Devesh Kumar Singh on Stack OverflowYou can use collections.defaultdict for a nested dictionary, where you define an initial value of a dictionary
from collections import defaultdict
#Use the initial value as a dictionary
dct = defaultdict(dict)
dct['a']['b'] = 'c'
dct['d']['e'] = 'f'
print(dct)
The output will be
defaultdict(<class 'dict'>, {'a': {'b': 'c'}, 'd': {'e': 'f'}})
You can create empty dict with {}:
d = {}
You can create dict of dict (as values) the way like the first:
d = {
1: {},
2: {}
}
You can modify the dict's value by []:
d = {1: 0}
d[1] = 1
d
{1: 1}
The similar with dict in dict:
d = {
1: {},
2: {}
}
d[1][4] = 5
d
{1: {4: 5}, 2: {}}
If you want to create a dict of dicts according to the list of keys, you can use dict comprehensions:
keys = [1,2,3,4,5]
d = {key: {} for key in keys}
d
{1: {}, 2: {}, 3: {}, 4: {}, 5: {}}
Why is it common in python to make an empty list or dict first?
Initializer for set, like dict {} and list []
Initializing a dictionary in python with a key value and no corresponding values - Stack Overflow
Creating a new dictionary in Python - Stack Overflow
Videos
Something I've never understood with python is why it is so common for an empty list to be created and then populated with something in a subsequent (or even more common next) line:
my_list = [] my_list = [i for i in range(1, 21)]
Obviously this is a really really toy example, but I'm consistently finding this in "production" code in multiple places. Is it pythonic? It's basically pure duplication so I doubt it. Is it some hacky "optimisation"? Is it a side effect of the code priorly being a for loop, then turned to a list comprehension but not tidied up right?
I honestly just feel ike I'm missing something key, with the amount of times and variety of places I see this pattern.
Use the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don't have a default value in mind.
Copyempty_dict = dict.fromkeys(['apple','ball'])
this will initialize empty_dict as:
Copyempty_dict = {'apple': None, 'ball': None}
As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:
Copydefault_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)
You could initialize them to None.