python - 如何将列表值添加到python中的现有字典

标签 python list dictionary

我试图将 score 的每个值添加到字典名称 i,e score[0] 到 names[0] 等等......

names=[{'id': 1, 'name': 'laptop'}, {'id': 2, 'name': 'box'}, {'id': 3, 'name': 'printer'}]
score = [0.9894376397132874, 0.819094657897949, 0.78116521835327]

输出应该是这样的

names=[{'id': 1, 'name': 'laptop','score':0.98}, {'id': 2, 'name': 'box','score':0.81}, {'id': 3, 'name': 'printer','score':0.78}]

如何实现?提前致谢

最佳答案

我会这样理解:

>>> [{**d, 'score':s} for d, s in zip(names, score)]
[{'id': 1, 'name': 'laptop', 'score': 0.9894376397132874}, {'id': 2, 'name': 'box', 'score': 0.819094657897949}, {'id': 3, 'name': 'printer', 'score': 0.78116521835327}]

关于python - 如何将列表值添加到python中的现有字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61907311/

相关文章:

python - 查找形状内的像素索引 : Opencv and Python

Python-根据列表中的位置/索引从字典中获取值

python - 将 pandas 列表列转换为矩阵表示(一次热编码)

c# - 在应用程序设置中保存字典并在启动时加载它

c# - 从 Dictionary<int, StringBuilder> 到表值 SqlParameter。如何?

python - 如何为Odoo 10字段创建动态域(将在表单加载之前给出)?

python - 在 Pandas 数据框中将两个时间列添加在一起?

python - 在 Python 中,Matplotlib 的 Contour 函数可以返回特定等高线的点吗?

c# - 重复遍历列表

python - 尝试迭代字典时出现类型错误: 'int' 不可迭代