簡體   English   中英

如何在 Forloop 中的 Python 中將 Append 字符串轉換為字典

[英]How To Append String To Dictionary in Python within Forloop

我需要 append 在 forloop 中的 python 中的字典中的特定鍵的字符串值 append,如果 forloop 中的數據為空,則給出我無法正確處理的空字符串的值,這里是一些代碼,

top100 = {}

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    # the value in the title is list of 100 title 
    # more like ['title1', 'title2', ...] and so the price [100, 230, ...]


    # how to append each pairs of title and price so i have list of dictionary
    
    top100['title'].append(title)
    top100['price'].append(price)


print( top100)

output:

KeyError: 'title'

但我需要更多類似的東西:

top100 = [{'title': 'title1', 'price': 'price1'}, 
          {'title': 'title2', 'price': 'price2'}
         ]  

top 100變量應該是一個列表,然后 append 一個字典

top100 = []

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    
    top100.append({'title':title,'price':price})


print( top100)

您需要使用以下代碼使top100成為一個包含許多嵌套字典的列表:

top100 = []
for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
    top100.append({'title':title,'price':price})

這里是另一個版本的結果

top100 = {'title':[],'price':[]}

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    
    top100['title'].append(title)
    top100['price'].append(price)


print( top100)

這應該是 output

{'title':[..., ..., ... ],'price':[..., ..., ...]}

感謝您的回答,我能夠找到自己的解決方案,

top100 = []
for product in product_list:
    titles = product.xpath('a[@class="someLink"]/text()')
    prices = product.xpath('div[@class="somePrice"]/text()')

    for title, price, in zip(titles, prices):
        top100.append({'title':title, 'price':price})

output:

top100 = [{'title': 'title1', 'price': '100'}, 
          {'title': 'title2', 'price': '200'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM