将字典附加到具有相同键和不同值的列表

问题描述 投票:0回答:2

从网站提取数据后,我想将其作为列表中的字典打印出来,但输出仅显示整个循环的第一次迭代,而不是打印所有整个循环迭代 这是我的代码:

list = []
for item in data:
        
        dictionary = {}
        dictionary['Address'] = item.find('div',{'class':'property-address'}).text.replace(' ','').strip()    
            
        dictionary['Locality'] = item.find('div',{'class':'property-city'}).text.replace(' ','').strip()
        dictionary['Beds'] = item.find('div',{'class':'property-beds'}).find('strong').text
        try:
            dictionary['Baths'] = item.find('div',{'class':'property-baths'}).find('strong').text
        except:
                pass  
        try: 
            dictionary['Square Feet'] = item.find('div',{'class':'property-sqft'}).find('strong').text
        except:
                pass     
        dictionary['Price'] = item.find('a',{'class':'listing-price'}).text.replace('\n','').replace(' ','')
        

list.append(dictionary)

执行代码后,我期望列表打印出循环的所有迭代,但字典只打印出第一个迭代而不是全部

The output of the code
[{'Address': '924MaltmanAve',
  'Locality': 'LosAngelesCA90026',
  'Beds': '1',
  'Baths': '1',
  'Square Feet': '676',
  'Price': '$825,000'}]

相反,它应该是这样的

[{'Address': '924MaltmanAve',
  'Locality': 'LosAngelesCA90026',
  'Beds': '1',
  'Baths': '1',
  'Square Feet': '676',
  'Price': '$825,000'},
{'Address': '3055NicholsCanyonRd',
  'Locality': 'LosAngelesCA90046',
  'Beds': '5',
  'Baths': '4',
  'Square Feet': '776',
  'Price': '$3,950,000'},
{'Address': '3055NicholsCanyonRd',
  'Locality': 'LosAngelesCA90046',
  'Beds': '5',
  'Baths': '4',
  'Square Feet': '776',
  'Price': '$3,950,000'}]

顺序如下。 但输出只给了我整个迭代的第一次迭代

做了很多研究,但没有好的答案,我正在寻找解决方案

python list dictionary
2个回答
0
投票

print(list)
吗?或者其他什么?


0
投票

list.append
的缩进更改为右侧。另外:

  • 不要使用内置名称,例如
    list
    (它掩盖了 Python 的
    list
    )。
  • 不要使用
    try: except: pass
    ,用
    if ... else
  • 处理缺失的元素
lst = []  # <-- don't use `list` as variable name
for item in data:

    dictionary = {}

    dictionary["Address"] = (
        item.find("div", {"class": "property-address"}).text.replace(" ", "").strip()
    )

    dictionary["Locality"] = (
        item.find("div", {"class": "property-city"}).text.replace(" ", "").strip()
    )
    dictionary["Beds"] = (
        item.find("div", {"class": "property-beds"}).find("strong").text
    )

    baths = item.select_one("div.property-baths strong")  # <-- don't use try: except: pass
    dictionary["Baths"] = baths.text if baths else "-"

    sfeet = item.select_one("div.property-sqft strong")
    dictionary["Square Feet"] = sfeet.text if sfeet else "-"

    dictionary["Price"] = (
        item.find("a", {"class": "listing-price"})
        .text.replace("\n", "")
        .replace(" ", "")
    )

    lst.append(dictionary)  # <-- note the indentation
© www.soinside.com 2019 - 2024. All rights reserved.