Reputation: 3
sorry if it's been asked, but I could not find the correct answer. I have 2 lists:
list1 = [1, 2, 3, 5, 8]
list2 = [100, 200, 300, 400, 500]
and a nested dictionary:
myDict = {
1: {'first': None, 'second': None, 'third': None} ,
2: {'first': None, 'second': None, 'third': None} ,
3: {'first': None, 'second': None, 'third': None} ,
5: {'first': None, 'second': None, 'third': None} ,
8: {'first': None, 'second': None, 'third': None} ,
}
How do I insert values in each of dictionaries inside myDict, based on key? Expected output:
myDict= {
1: {'first': 100, 'second': None, 'third': None} ,
2: {'first': 200, 'second': None, 'third': None} ,
3: {'first': 300, 'second': None, 'third': None} ,
5: {'first': 400, 'second': None, 'third': None} ,
8: {'first': 500, 'second': None, 'third': None} ,
}
what I tried:
for i in list1:
for j in list2:
myDict[i]['first'] = j
print(myDict)
What I get (it replaces all values with the last item in the list)
{1: {'first': 500, 'second': None, 'third': None},
2: {'first': 500, 'second': None, 'third': None},
3: {'first': 500, 'second': None, 'third': None},
5: {'first': 500, 'second': None, 'third': None},
8: {'first': 500, 'second': None, 'third': None}
}
Thank you
Upvotes: 0
Views: 121
Reputation: 5314
Something like this would work:
i = 0
while i < len(list1):
myDict[list1[i]]["first"] = list2[i]
i += 1
Result:
{ 1: {'first': 100, 'second': None, 'third': None},
2: {'first': 200, 'second': None, 'third': None},
3: {'first': 300, 'second': None, 'third': None},
5: {'first': 400, 'second': None, 'third': None},
8: {'first': 500, 'second': None, 'third': None}}
Upvotes: 0
Reputation: 21
You can do the following:
for k,i in zip(list1,list2):
myDict[k]['first'] = i
and the output:
{1: {'first': 100, 'second': None, 'third': None},
2: {'first': 200, 'second': None, 'third': None},
3: {'first': 300, 'second': None, 'third': None},
5: {'first': 400, 'second': None, 'third': None},
8: {'first': 500, 'second': None, 'third': None}}
Upvotes: 0
Reputation: 455
What you need is zip
for i, j in zip(list1, list2):
myDict[i]['first'] = j
Upvotes: 5