0

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

1
  • you're creating a new dict every loop, instead of adding to an existing dictionary Commented Nov 2, 2018 at 22:28

3 Answers 3

2

To use your existing loop (though @N Chauhan has a good dictionary comprehension):

for dictionary in fetcher.fetch():
    dict[dictionary.title] = dictionary.image
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

You can assign to an individual dictionary entry to add: var[key]=value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.