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

在for循环中向字典追加值,python,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我对dictionary元素有点不熟悉,并且有一个关于在dict循环中附加键、值对的查询。 更新覆盖dict中的最后一个值 样本输入: 名称对象是示例输入,名称和文本将来自不同的对象 names = [ 'name23.pdf','thisisnew.docx','journey times.docx','Sheet 2018_19.pdf', 'Essay.pdf' ] 预期产出: {'name': 'name23.pdf', 'text': 'text1'} {'name': 't

我对dictionary元素有点不熟悉,并且有一个关于在dict循环中附加键、值对的查询。 更新覆盖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)
这是你想要的吗

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循环,则可以执行以下操作:

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值与列表中最后一个元素匹配的字典。为什么?因为字典中的键必须是唯一的,并且每个键只能有一个值

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

你到底想做什么?您是否可以共享预期的输出?您是否知道字典每个键只有一个值?您是否打算将该值作为列表并附加到列表中?最近的编辑并未真正清除您打算执行的操作。显示的代码似乎已经生成了例外输出。附加到什么?您只能附加到列表,而不能附加到dict。请将您的问题作为单个Python文本包含预期的输出。您必须解释您认为dict是如何工作的,因为我认为您并不真正理解,我希望使用此输出在for循环内创建dict对象