Ari
Ari

Reputation: 6199

creating a dictionary of dictionaries

I have the below code:

list_one = ['a', 'b']
list_two = ['1', '2']
list_three = {}

what I want to end up with is:

list_three = {
        'a':{1:[], 2:[]},
        'b':{1:[], 2:[]}
    }

I'm trying some crazy FOR x IN y loops but not getting the reuslt I want

Upvotes: 1

Views: 69

Answers (2)

RoadRunner
RoadRunner

Reputation: 26335

You could always make a nested collections.defaultdict() of lists:

from collections import defaultdict
from pprint import pprint

list_one = ['a', 'b']
list_two = ['1', '2']

d = defaultdict(lambda : defaultdict(list))

for x in list_one:
    for y in list_two:
        d[x][int(y)]

pprint(d)

Which will automatically initialize a list inside for you:

defaultdict(<function <lambda> at 0x000002AEA8D4C1E0>,
            {'a': defaultdict(<class 'list'>, {1: [], 2: []}),
             'b': defaultdict(<class 'list'>, {1: [], 2: []})})

You can then append values to these inner lists, since defaultdict() initialised empty lists for you.

Addtionally, you can also use dict.setdefault() here aswell:

list_one = ['a', 'b']
list_two = ['1', '2']

d = {}
for x in list_one:
    d.setdefault(x, {})
    for y in list_two:
        d[x].setdefault(int(y), [])

print(d)
# {'a': {1: [], 2: []}, 'b': {1: [], 2: []}}

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71610

Use nested-dictionary-comprehension:

print({k:{int(k2):[] for k2 in list_two} for k in list_one})

Output:

{'a': {1: [], 2: []}, 'b': {1: [], 2: []}}

Upvotes: 5

Related Questions