使用For循环创建编号字典[python]

2024-10-01 09:40:52 发布

您现在位置:Python中文网/ 问答频道 /正文

对于18个不同的链接,我尝试创建18个不同的字典(链接中划分的每一块土地对应一个字典),每个字典都包含人口、面积中的住房单元等统计数据的键和值。键是统计数据的名称,值是值。我写了一部分,遍历了所有18个链接,检索了人口和住房单元(以及它们的值),但我不知道如何制作字典。我试着使用for循环,比如:

def bgScrape(self):
        i = 0
        for l in self.hrefs:
            html = urlopen('http://www.usa.com' + l)
            soup = BeautifulSoup(html.read(), 'lxml')
            stat = soup.find('table')
            stat = stat.find_next('table')
            population = stat.find('td')
            population = population.find_next('td')
            population1 = population.find_next('a')
            population1 = population1.find_next('a')
            houseunits = population1.find_next('td')
            houseunits1 = population1.find_next('a')
            print(houseunits1)
            for i in range(18):
                stats[i] = {}
                stats[i]['Population'] = population1.text

但是这给了我NameError: name 'stats' is not defined,这让我相信你不能像这样在For循环中创建字典。是这样,还是我写错了?还是有更好的方法完全实现这个目标?你知道吗


Tags: selffor字典链接statsfindstat统计数据
1条回答
网友
1楼 · 发布于 2024-10-01 09:40:52

你可以替换整个第二个循环

for i in range(18):
    stats[i] = {}
    stats[i]['Population'] = population1.text

签署人:

stats = [{'Population' : population1.text} for i in range(18)]

相关问题 更多 >