首页 > 解决方案 > 如何在 Forloop 中的 Python 中将字符串附加到字典

问题描述

我需要将字符串的值附加到forloop中python字典中的特定键,如果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)

输出:

KeyError: 'title'

但我需要更多类似的东西:

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

标签: python

解决方案


top 100变量应该是一个列表,然后附加一个字典

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)

推荐阅读