对象已由网站搜寻器创建。在此示例中,存储了 title 和 image 文件路径。输出如下:
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
目标是将 title 作为键存储,将 image 路径作为值存储在字典中
dict = {}
for dictionary in fetcher.fetch():
dict = {dictionary.title: dictionary.image}
print(dict)
{'Open-architected secondary product': './img/7.jpg'}
问题:字典中仅存储最后一项。我的代码有什么问题?
谢谢
答案 0 :(得分:2)
使用现有循环(尽管@N Chauhan具有很好的字典理解力):
for dictionary in fetcher.fetch():
dict[dictionary.title] = dictionary.image
答案 1 :(得分:1)
您的问题是因为您每次迭代都覆盖dict
。改用字典理解:
article_info = {article.title: article.image
for article in fetcher.fetch()}
旁注:始终避免将内置名称用作变量,就像您将dict
用作变量名一样。只需选择一个更具描述性的名称-最终将以两种方式受益:
dict
类未隐藏。 答案 2 :(得分:0)
您可以分配给单个词典条目来添加: var [key] = value