簡體   English   中英

從列表中編輯嵌套字典中的值(python)

[英]Edit values in nested dictionary from the list (python)

對不起,如果有人問過,但我找不到正確的答案。 我有 2 個列表:

list1 = [1, 2, 3, 5, 8]
list2 = [100, 200, 300, 400, 500]

和一個嵌套字典:

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} ,
    }

如何根據鍵在 myDict 中的每個字典中插入值? 預計 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} ,
    }

我試過的:

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

我得到了什么(它將所有值替換為列表中的最后一項)

{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}
}

謝謝

你需要的是zip

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

您可以執行以下操作:

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

和 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}}

這樣的事情會起作用:

i = 0 
while i < len(list1):
myDict[list1[i]]["first"] = list2[i]
i += 1

結果:

{  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}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM