I have three lists (of lists) - index_1
, index_2
and index_3
. I want to combine them to make a nested dictionary. The keys of the top level of the dictionary should be index_1 = ['item1','item2','item3']
. The second level should be keyed by index_2
(which has 3 elements corresponding to 'item1'
, 'item2'
, and 'item3'
). The values in the second level of the dictionary should contain values and be stored in a list as in index_3
.
I am a bit stuck and think I am creating overly complicated loops shown below. Any comments would be great.
# input lists
index_1 = ['item1', 'item2', 'item3']
index_2 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
index_3 = [[0, 1, 2, 3, 4], [99, 100], [0, 1, 2]]
# desired output
my_dict = {'item1' : {'a' : [0, 1, 2, 3, 4], 'b' : [0, 1, 2, 3, 4], 'c' : [0, 1, 2, 3, 4]},
'item2' : {'d' : [99, 100], 'e' : [99, 100], 'f' : [99, 100]},
'item3' : {'g' : [0, 1, 2], 'h' : [0, 1, 2], 'i' : [0, 1, 2]}}
# my loop that didnt work
d = defaultdict(defaultdict)
for i in range(len(index_1)):
for x, y, z in zip([index_1[i]], [index_2[i]], [index_3[i]]):
d[x][y] = [z]