Python - Store a value in an array inside one for loop

80,012

Define a list and append to it:

prices = []
for item in world_dict:
     if item[1] == 'House':
       price = float(item[2])
       prices.append(price)

print(price)

or, you can write it in a shorter way by using list comprehension:

prices = [float(item[2]) for item in world_dict if item[1] == 'House']
print(prices)

Hope that helps.

Share:
80,012
A. Ayres
Author by

A. Ayres

Updated on December 07, 2021

Comments

  • A. Ayres
    A. Ayres over 2 years

    I would like to store each value of price in an array, getting it from a dict. I am a fresh at python, I spent hours trying to figure this out...

    for item in world_dict:
         if item[1] == 'House':
           price = float(item[2])
           print p
    
    The output is like:
    200.5
    100.7
    300.9
    ...
    n+100
    

    However, I want to store it on this format : [200.5, 100.7, 300.9, ..., n+100]

  • A. Ayres
    A. Ayres about 10 years
    I appreciate your help very much. Thank you. It was exactly I was looking ofr