【问题标题】:Append values to dictionary in for loop, python在for循环中将值附加到字典,python
【发布时间】:2020-09-19 13:33:00
【问题描述】:

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

示例输入:

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

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)

【问题讨论】:

  • 你到底想做什么?你能分享一个预期的输出吗?
  • 你知道字典的每个键只有一个值吗?您是否打算将该值设为列表并附加到它?
  • 最近的编辑并没有真正弄清楚你打算做什么。显示的代码似乎已经产生了异常输出。
  • 追加到什么?您只能附加到列表,而不是字典。请edit您的问题将预期输出包含为单个 Python 文字。
  • 你必须解释你认为 dict 是如何工作的,因为我认为你并没有真正理解

标签: python python-3.x dictionary


【解决方案1】:

这是你想要的吗?

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)

输出将与上面相同。

但是,使用您的方法将仅生成 one 字典,其值 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'}

【讨论】:

  • 我想用这个输出在 for 循环中创建一个 dict 对象
猜你喜欢
  • 2021-05-19
  • 1970-01-01
  • 2019-06-14
  • 2016-12-12
  • 2016-10-14
  • 2022-08-17
  • 2019-07-26
  • 1970-01-01
  • 2020-05-20
相关资源
最近更新 更多