简体   繁体   English

如何在 Forloop 中的 Python 中将 Append 字符串转换为字典

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

i need to append a value of string to a specific key in dictionary in python within forloop, and if the data in forloop is empty then give the value of empty string which i'm not able to get it right, here is some of the code,我需要 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: output:

KeyError: 'title'

but i need something more like:但我需要更多类似的东西:

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

The top 100 variable should be a list, then append a dictionary 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)

You need to make top100 a list with many nested dictionaries, with the following code:您需要使用以下代码使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})

Here for the another version of result这里是另一个版本的结果

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)

This should output这应该是 output

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

thanks for the answer i was able to find my own solution,感谢您的回答,我能够找到自己的解决方案,

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: output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM