首页 > 解决方案 > Edit values in nested dictionary from the list (python)

问题描述

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

标签: pythonlistdictionary

解决方案


What you need is zip

for i, j in zip(list1, list2):
   myDict[i]['first'] = j

推荐阅读