在for循环中向字典追加值,python

2024-05-13 04:40:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我对dictionary元素有点不熟悉,并且有一个关于在dict循环中附加键、值对的查询。 dict.update()覆盖dict中的最后一个值

样本输入:

名称对象是示例输入,名称和文本将来自不同的对象

names = [    'name23.pdf','thisisnew.docx','journey times.docx','Sheet 2018_19.pdf', 'Essay.pdf' ] 

预期产出:

{'name': 'name23.pdf', 'text': 'text1'}
{'name': 'thisisnew.docx', 'text': 'To be filled'}
{'name': 'journey times.docx', 'text': 'To be filled'}
{'name': 'Sheet 2018_19.pdf', 'text': 'To be filled'}
{'name': 'Essay.pdf', 'text': 'To be filled'}


final_dict = {}
for name in names:
    name = {'name': name,'text' : 'To be filled'}
    final_dict.update(name)
    print(final_dict)

Tags: to对象textname名称pdfnamesupdate
1条回答
网友
1楼 · 发布于 2024-05-13 04:40:17

这是你想要的吗

names = ['name23.pdf', 'thisisnew.docx', 'journey times.docx', 'Sheet 2018_19.pdf', 'Essay.pdf']
print([{"name": n, "text": "To be filled"} for n in names])

输出:

[{'name': 'name23.pdf', 'text': 'To be filled'}, {'name': 'thisisnew.docx', 'text': 'To be filled'}, {'name': 'journey times.docx', 'text': 'To be filled'}, {'name': 'Sheet 2018_19.pdf', 'text': 'To be filled'}, {'name': 'Essay.pdf', 'text': 'To be filled'}]

如果您想要一个for loop,则可以执行以下操作:

names = ['name23.pdf', 'thisisnew.docx', 'journey times.docx', 'Sheet 2018_19.pdf', 'Essay.pdf']

output = []
for name in names:
    output.append({'name': name, 'text': 'To be filled'})

print(output)

输出将与上面相同

但是,使用您的方法将只生成值为name与列表中最后一个元素匹配的one字典。为什么?因为字典中的键必须是唯一的,并且每个键只能有一个值

names = ['name23.pdf', 'thisisnew.docx', 'journey times.docx', 'Sheet 2018_19.pdf', 'Essay.pdf']

final_dict = {}
for name in names:
    final_dict.update({'name': name, 'text': 'To be filled'})
    print(final_dict)

print(f"Final result: {final_dict}")

结果:

{'name': 'name23.pdf', 'text': 'To be filled'}
{'name': 'thisisnew.docx', 'text': 'To be filled'}
{'name': 'journey times.docx', 'text': 'To be filled'}
{'name': 'Sheet 2018_19.pdf', 'text': 'To be filled'}
{'name': 'Essay.pdf', 'text': 'To be filled'}

Final result: {'name': 'Essay.pdf', 'text': 'To be filled'}

相关问题 更多 >