Adding values to dictionary in FOR loop. Updating instead of “Appending”

半腔热情 提交于 2020-05-17 07:44:08

问题


import requests
from bs4 import BeautifulSoup

urls = ['url1']
dictionary = {}

for url in urls:
    req = requests.get(url)
    soup = BeautifulSoup(req.text, "lxml")

    for sub_heading in soup.find_all('h3'):  
        dictionary[url] = sub_heading.text

print(dictionary)

I'm getting a result that looks like this {url : sub_heading.text} instead of getting a dictionary containing all the values I'm expecting. It seems that the loop is updating instead of "appending"...


回答1:


Python Dictionaries have key:value pairs, and it can not have duplicate keys.

So in this code, 'url' is key and 'sub_heading.text' is value.

And everytime this loop runs, only the value for 'url' in dict is getting updated.

 for sub_heading in soup.find_all('h3'):  
        dictionary[url] = sub_heading.text

You should use some other data structure instead of Dict (for e.g. list of tuples or dataframe).



来源:https://stackoverflow.com/questions/61374655/adding-values-to-dictionary-in-for-loop-updating-instead-of-appending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!