python - 将列表中的项目添加到另一个列表中的字典

标签 python python-3.x

<分区>

我正在尝试将列表中的项目添加到另一个列表中的词典中。

info = [{'id' : 1, 'tag' : 'Football'}, {'id' : 2, 'tag' : 'MMA'}]
dates = ['May 1st', 'April 23rd']
for item in dates:
   for dic in info:
       dic['date'] = item

这是我想要得到的:

[{'id': 1, 'tag': 'Football', 'date': 'May 1st'},
 {'id': 2, 'tag': 'MMA', 'date': 'April 23rd'}]

但我得到的不是它:

[{'id': 1, 'tag': 'Football', 'date': 'April 23rd'},
 {'id': 2, 'tag': 'MMA', 'date': 'April 23rd'}]

请指正。

最佳答案

如果您嵌套 for 循环,那么只有第一个 for 的最后一次迭代很重要。

正确的做法是使用函数 zip 在两个列表上并行循环。

info = [{'id' : 1, 'tag' : 'Football'}, {'id' : 2, 'tag' : 'MMA'}]
dates = ['May 1st', 'April 23rd']
for item,dic in zip(dates,info):
    dic['date'] = item

关于python - 将列表中的项目添加到另一个列表中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72336212/

相关文章:

python - 试图理解 Python 中的抽象工厂模式

python - 在 anaconda 中安装 OpenCV 未显示在 Windows 10 的 VS Code 中

Python pandas 替换函数不适用于转义字符

mysql - 如何解决 django.db.utils.IntegrityError : (1364, "Field ' name' doesn't have a default value")

python-3.x - 使用 Python3 ncclient/paramiko 时出错?

python - print() 与 sys.stdout.write() : which and why?

javascript - 变量为 0 时的乘法赋值运算符

python - 如何在 python 中将 <None> 类型对象的输出重定向到文本文件?

python - 在 VS Code 中选择 python 解释器时出现错误 : spawn ENOTDIR,

python-3.x - Python - KeyError(key) 被引发,但它不应该