我尝试做字典循环。 例如
A = {"Name":1,"Price":2}
B = {"Name":3,"Price":6}
C = {"Name":"","Price":3}
我想要一起添加A B和C
C = {"Name":[1,3,],"Price":[2,6,3]}
我该怎么做?谢谢 这是我尝试从住宿页面获取数据的实际代码。它仍然缺少我将所有数据字典放在一起并循环到下一页的部分,并且顺便感谢你。
from bs4 import BeautifulSoup as soup
import re
from selenium import webdriver
driver = webdriver.Firefox()
my_url = 'https://www.hipflat.co.th/en/search/sale/condo_y/any_r1/any_r2/any_p/any_b/any_a/any_w/any_o/any_i/100.62442610451406,13.77183154691727_c/12_z/list_v'
driver.get(my_url)
html = driver.page_source
page_soup = soup(html)
#Grab Condo
Condo = page_soup.findAll("li",{"class":"listing"})
for Con in Condo:
Name = Con.findAll("div",{"class":"listing-project"})[0].text.strip()
Description = Con.p.text
Price = Con.findAll("div",{"class":"listing-price"})[0].text.strip()
Type = Con.findAll("ul",{"class":"listing-detail"})[0].text.replace("\n","")
Type = [Name]+[Price]+[Description]+re.split(r'(bed|bath|m2)',Type)
Data = {"Name" : Name,"Description" : Description,"Price":Price,"Bed":Type[3],"Bath":Type[5],"Area(m2)":Type[7],"Floor":Type[9]}
print(Data)
next_page = driver.find_element_by_xpath('//*[@id="page-content"]/div[2]/div/div[2]/div[1]/div[2]/div/div[3]/a[1]').click()
答案 0 :(得分:1)
你可以循环键(其中一个键)。
indicts = [{}, {}...]
outdict = {}
for k in indicts[0].keys():
outdict[k] = [d[k] for d in indicts]
答案 1 :(得分:0)
组合这样的词组的基本方法是检查键是否在结果字典中,如果是,则将值添加到列表中,否则如果键不存在,则添加新列表有价值。
result = {}
for dicti in (A, B, C):
for key, value in dicti.items():
if key in result:
result[key].append(value)
else:
result[key] = [value]
这样做的现代方法是使用collections.defaultdict
list
作为default_factory
函数传递。它与上面基本相同,如果缺少密钥,则插入一个带有值的新列表。
from collections import defaultdict
result = defaultdict(list)
for dicti in (A, B, C):
for key, value in dicti.items():
result[key].append(value)