Home > Net >  for-loop through a dict within a dict
for-loop through a dict within a dict

Time:01-17

I am having trouble with the below code:

{'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'}]

total = 0
count = 0

product_search = input('product: ')
for d in l:
    name = d['name']
    for _, item in d.items():
        if item == product_search:
            total  = int(d['price'])
            count  = 1
            print(d['name'],d['price'])

print('average price of a {} is: {}'.format(name, total / count))

I am looking for the most efficient way to search the below without printing on each iteration of the for loop.

I have devised the below code but the output iterates over each dict and prints the output 'not in list'.

product_search = input('product: ')
for d in l:
    name = d['name']
    for _, item in d.items():
        if item == product_search:
            total  = int(d['price'])
            count  = 1
            print(d['name'],d['price'])
        if product_search != item:
            print('not in list')

print('average price of a {} is: {}'.format(name, total / count))

CodePudding user response:

I would try something like this:

from statistics import fmean
product_search = input('product: ')
avg = mean(
    int(d['price'])
    for d in l
    if d['name'] == product_search
)
print(f'average price of a {product_search} is: {avg}')

Output

product:  apple

average price of a apple is: 506.6666666666667

CodePudding user response:

import statistics as stats

l = [{'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'}]

product = 'apple'

prices = [float(d['price']) for d in l if d['name'] == product]

mean_price = stats.mean(prices) if len(prices) > 0 else None

if mean_price is not None:
    print(f'The mean price of {product} is {mean_price:.2f}')
else:
    print('Not in list')

Edit:

I think your code snippet is missing an "l = [" at the very beginning, in which case you are actually looking at a list of dictionaries not a dictionary of dictionaries. Not a big deal, just want to make sure the terminology is straight.

As for your code itself, the first for loop is fine. However, in the second for loop, you are actually looking through each dictionary item when you only need to look at the 'name' key in the dictionary.

For example, when you look at the first dictionary, you are comparing 2 == product and then 'apple' == product then '150' == product, etc... You really only need "if name == product" That's why you are printing a lot of "not in list" because you are comparing apples to oranges so to speak.

Finally, it's a small thing, but your two if statements can be turned into an if-else combination instead since if it fails the first test, it automatically passes the second. If you use two if-statements that are covering the same essential test, the code will check twice. It's an extremely minor efficiency issue for this problem, but it's a good habit to make sure you're not over-testing with if statements.

  • Related