4

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
martineau
  • 119,623
  • 25
  • 170
  • 301
Joe
  • 11,983
  • 31
  • 109
  • 183
  • You're going to need a nested dictionaries—a dictionary-of-dictionaries—to do that. – martineau Aug 03 '18 at 20:57
  • And that's what the accepted answer does (as well as @LemonPi's) — `defaultdict` is a subclass (i.e. specialized) dictionary which in this case is being used to automatically create the sub-dictionaries whenever something is first assigned to one to one of its keys. Check out the [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) documentation. – martineau Aug 03 '18 at 21:08

4 Answers4

10

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}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

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

LemonPi
  • 1,026
  • 9
  • 22
0

You need to create nested dicts:

d = {'a1': {'b1': 1, 'b2': 2}, 'a2': {'b1': 3, 'b2': 4}}

And then just:

for k, v in d['a1'].items():
    print(k, v)
Lev Zakharov
  • 2,409
  • 1
  • 10
  • 24
-1

That's not one dict; it's a dict that has other dicts as values.

d['a1'] = {'b1': 1}
d['a1'] = {'b2': 2}
d['a2'] = {'b1': 3}
d['a2'] = {'b2': 4}

From there, you can work with each of the nested dicts as you would any other value. For example

for k1, v1 in d.items():
    for k2, v2 in v1.items():
        print("{} -> {} -> {}".format(k1, k2, v2))    
chepner
  • 497,756
  • 71
  • 530
  • 681