繁体   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