简体   繁体   English

通过for循环从多个对象向字典添加键和值

[英]add keys and values to a dictionary from multiple objects by for loop

Objects has been created by a website crawler. 对象已由网站搜寻器创建。 In this example, a title and the image file path is stored. 在该示例中, 标题图像文件路径被存储。 The output is as following: 输出如下:

for article in fetcher.fetch():
    print(article.title + " | " + article.image)

Polarised modular conglomeration | ./img/1.jpg
Cross-group contextually-based middleware | ./img/2.jpg
De-engineered encompassing structure | ./img/3.jpg
Fully-configurable multi-tasking interface | ./img/4.jpg
Versatile eco-centric core | ./img/5.jpg
Optional maximized utilisation | ./img/6.jpg
Open-architected secondary product | ./img/7.jpg

The goal is to store title as key and image path as value in a dictionary 目标是将标题作为键存储,将图像路径作为值存储在字典中

dict = {}

for dictionary in fetcher.fetch():
    dict = {dictionary.title: dictionary.image}

print(dict)
{'Open-architected secondary product': './img/7.jpg'}

Problem: Only the last item is stored in the dictionary. 问题:只有最后一项存储在词典中。 What is wrong with my code? 我的代码有什么问题?

Thank you 谢谢

To use your existing loop (though @N Chauhan has a good dictionary comprehension): 要使用您现有的循环(尽管@N Chauhan具有很好的字典理解力):

for dictionary in fetcher.fetch():
    dict[dictionary.title] = dictionary.image

Your problem is because you're overwriting the dict each iteration. 您的问题是因为您每次迭代都覆盖dict Use a dictionary comprehension instead: 请改用字典理解:

article_info = {article.title: article.image
                for article in fetcher.fetch()}

Side note: always refrain from using built-in names as variables like your use of dict as a variable name. 旁注:始终避免将内置名称用作变量,就像将dict作为变量名称一样。 Just pick a more descriptive name - this will ultimately benefit in 2 ways: 只需选择一个更具描述性的名称-最终将通过两种方式受益:

  • the default dict class is not shadowed. 默认的dict类不会被遮盖。
  • you have a better idea of what the variable is if you give it a good name instead of a vague one. 如果给它一个好名字而不是一个模糊的名字,那么您对变量是什么有一个更好的了解。

您可以分配给单个词典条目以添加:var [key] = value

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

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