简体   繁体   中英

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,

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'

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

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 = []
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

{'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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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