Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dict with 2 keys and one value?

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
like image 366
Joe Avatar asked Oct 23 '25 18:10

Joe


2 Answers

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}
like image 182
Andrej Kesely Avatar answered Oct 26 '25 06:10

Andrej Kesely


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'] = {}.

like image 26
LemonPi Avatar answered Oct 26 '25 06:10

LemonPi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!