【问题标题】:Edit values in nested dictionary from the list (python)从列表中编辑嵌套字典中的值(python)
【发布时间】:2020-07-30 02:44:52
【问题描述】:

对不起,如果有人问过,但我找不到正确的答案。我有 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 中的每个字典中插入值? 预期输出:

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

谢谢

【问题讨论】:

  • 你实际上做了 25 次更新而不是 5 次,每个键在 list2 中的每个值更新一次
  • @Chris 谢谢,我以为出了点问题

标签: python list dictionary


【解决方案1】:

你需要的是 zip

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

【讨论】:

  • 谢谢!我以前从未使用过 zip,这确实是一个有用的东西 :) 将阅读更多关于它的文档
【解决方案2】:

您可以执行以下操作:

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

和输出:

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

【讨论】:

    【解决方案3】:

    这样的事情会起作用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多