【问题标题】:Merging a list into a dictionary and giving it a specific key name python 3将列表合并到字典中并给它一个特定的键名python 3
【发布时间】:2019-02-22 22:25:04
【问题描述】:

我正在使用 Python 3 以列表的形式获取一些值。这些值可以是浮点数、字符串,甚至是None。例如,我可以有一个类似的列表:

value = [ None, 1.2, 1.44, 'test', 9 ]

我有一个与此列表中的条目数量相匹配的字典,我想循环遍历该字典,向该字典添加值并为其指定一个特定键。

所以,如果我的字典是这样的:

di = [ 
   {'date' : '01/01/2019', 'info' : 'hello' },
   {'date' : '01/02/2019', 'info' : 'world' },
   {'date' : '01/03/2019', 'info' : 'test'  },
   {'date' : '01/04/2019', 'info' : 'no'    },
   {'date' : '01/05/2019', 'info' : 'yes'   }
]

我想遍历 value 并将每个项目推送到 di 中的特定键中,这样 di 看起来像这样:

di = [ 
  {'date' : '01/01/2019', 'info' : 'hello', 'update' : 'None' },
  {'date' : '01/02/2019', 'info' : 'world', 'update' : 1.2    },
  {'date' : '01/03/2019', 'info' : 'test',  'update' : 1.44   },
  {'date' : '01/04/2019', 'info' : 'no',    'update' : 'test' },
  {'date' : '01/05/2019', 'info' : 'yes',   'update' : 9      }
]

我查看了其他一些答案,有两种方法看起来可以做到这一点:

方法一:

for k, *v in value:
    data[k]['update'] += v

返回:TypeError: 'NoneType' object is not iterable

方法二:

for i, v in value:
    data[i]['update'] = v

返回:TypeError: 'NoneType' object is not iterable

所以,这个None 值(我需要它)显然与迭代值混淆了。有什么方法可以循环 value 并使用 Python 3 中的简单方法将该值附加到我的字典中?

【问题讨论】:

    标签: python loops dictionary


    【解决方案1】:
    for newval, dic in zip(values, di):
        dic['update'] = newval
    

    zip 是将每个值与您需要更新的字典相关联的关键。它让for 循环从两个列表中各取一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 2020-10-14
      • 2013-03-19
      • 1970-01-01
      • 2018-10-04
      • 2021-01-10
      • 2017-04-11
      相关资源
      最近更新 更多