简体   繁体   English

将值附加到 for 循环中的字典,python

[英]Append values to dictionary in for loop, python

I am a bit lousy with dictionary elements and have a query on appending key,value pairs in dict in a loop.我对字典元素有点糟糕,并且有一个关于在循环中在 dict 中附加键、值对的查询。 dict.update() overwrites the last value in the dict. dict.update() 覆盖 dict 中的最后一个值。

Sample input:样本输入:

names object is the sample input with name and text will come from different object名称对象是带有名称和文本的示例输入将来自不同的对象

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

Expected Output:预期输出:

{'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)

Is this what you want?这是你想要的吗?

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])

Output:输出:

[{'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'}]

If you want a for loop then you can do this:如果你想要一个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)

The output is going to be the same as above.输出将与上面相同。

However, using your approach will produce only one dictionary with the value of name matching the last element from the list.但是,使用您的方法将仅生成one字典,其name值与列表中的最后一个元素匹配。 Why?为什么? Because keys in a dictionary have to be unique and each key can have only one value.因为字典中的键必须是唯一的,并且每个键只能有一个值。

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}")

Result:结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM