Home > Software design >  python dictionaries within a list
python dictionaries within a list

Time:01-17

I have the below dictionaries within a list:

price_list = [
     {'id': 1, 'name': 'apple', 'price': '100', 'year': '2000', 'currency': 'eur'},
     {'id': 2, 'name': 'apple', 'price': '150', 'year': '2022', 'currency': 'eur'},
     {'id': 3, 'name': 'apple', 'price': '1220', 'year': '160', 'currency': 'eur'},
     {'id': 4, 'name': 'apple', 'price': '150', 'year': '2080', 'currency': 'eur'}
]

The below code calculates the average price of the list:

for d in price_list:
    for _,item in d.items():
        total  = int(d['price'])
        count  = 1
        print(total,count)
        print('average=', total / count)

I want to be able to ignore anything within 10 years of the mid. So if i had an input of year = 2020, when querying against my list i will only want search back to 2010 and anything forward to 2030. Is this possible to implement?

CodePudding user response:

Look up the year and test it for the year range, then if it is an 'apple' then add the price so you calculate the average.

l = [{'id': 1, 'name': 'apple', 'price': '100', 'year': '2000', 'currency': 'eur'},    {'id': 2, 'name': 'apple', 'price': '150', 'year': '2022', 'currency': 'eur'},    {'id': 3, 'name': 'apple', 'price': '1220', 'year': '160', 'currency': 'eur'},    {'id': 4, 'name': 'apple', 'price': '150', 'year': '2080', 'currency': 'eur'}]

mid_year = 2020

total = 0
count = 0
for d in l:
    if int(d['year']) >= mid_year-10 and int(d['year']) <= mid_year 10:
        if d['name'] == 'apple':
            total  = int(d['price'])
            count  = 1

print('average=', total / count)

Runnable code: https://trinket.io/python3/1ab1232e44

CodePudding user response:

You can use a short for to make it one line

price = [int(d['price']) for d in price_list if int(d['year'])>year-10 and int(d['year'])<year 10]
print('average=', sum(price)/len(price)

  • Related