In python I can define dictionary as:
d = {}
and store data as:
d['a1'] = 1
How to store 2 keys?
d['a1']['b1'] = 1
d['a1']['b2'] = 2
d['a2']['b1'] = 3
d['a2']['b2'] = 4
and then print all keys and values for e.g. d['a1'] which would be:
b1 -> 1
b2 -> 2
You can use defaultdict from collections module (docs here):
from collections import defaultdict
d = defaultdict(dict)
d['a1']['b1'] = 1
d['a1']['b2'] = 2
d['a2']['b1'] = 3
d['a2']['b2'] = 4
print(d['a1'])
Prints:
{'b1': 1, 'b2': 2}
You can use collections.defaultdict but you cannot mix an int and dict assignment to d['a1'] as in your example.
from collections import defaultdict
d = defaultdict(dict)
d['a1']['b1'] = 1
d['a1']['b2'] = 2
d['a2']['b1'] = 3
d['a2']['b2'] = 4
d['a3'] = 1
print(d['a1'])
print(d['a3'])
>>> {'b1': 1, 'b2': 2}
>>> 1
If you really want to first assign 1 to d['a1'] then change it to a dictionary, you'll have to manually do that after the assignment with d['a1'] = {}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With