简体   繁体   中英

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

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

Your problem is because you're overwriting the dict each iteration. 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. Just pick a more descriptive name - this will ultimately benefit in 2 ways:

  • the default dict class is not shadowed.
  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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