I have a nested dictionary which contains the data about books:
Here is the definition:
books = {
'uid1':
{'price': '100',
'condition': 'good'},
'uid2':
{'price': '80',
'condition': 'fair'},
'uid3':
{'price': '150',
'condition': 'excellent'},
'uid4':
{'price': '70',
'condition': 'fair'},
'uid5':
{'price': '180',
'condition': 'excellent'},
'uid6':
{'price': '60',
'condition': 'fair'}
}
I need to get average prices, grouped by condition. So, the intended result is:
{'fair': 70, 'good': 100, 'excellent': 165}
What is the most Pythonic way to do it?
Using collections.defaultdict
Demo:
from collections import defaultdict
res = defaultdict(list)
for k,v in books.items():
res[v['condition']].append(int(v['price']))
print({k: sum(v)/len(v) for k, v in res.items() })
Output:
{'good': 100, 'fair': 70, 'excellent': 165}
I would like to answer this question using Pandas Library.
import pandas as pd
books = {
'uid1':
{'price': '100',
'condition': 'good'},
'uid2':
{'price': '80',
'condition': 'fair'},
'uid3':
{'price': '150',
'condition': 'excellent'},
'uid4':
{'price': '70',
'condition': 'fair'},
'uid5':
{'price': '180',
'condition': 'excellent'},
'uid6':
{'price': '60',
'condition': 'fair'}
}
data = pd.DataFrame.from_dict(books, orient='index')
data['price'] = data[['price']].apply(pd.to_numeric)
data.groupby(['condition'])['price'].mean()
Output:
condition
excellent 165
fair 70
good 100
Here is one approach:
from statistics import mean
result = {condition: mean(float(book['price']) for book in books.values() if book['condition'] == condition) for condition in ('fair','good','excellent')}
#result = {'fair': 70.0, 'good': 100.0, 'excellent': 165.0}
I don't see why you need defaultdict
except for not using Try Except
-
for k, v in books.items():
try:
avg[v['condition']].append(int(v['price']))
except KeyError:
avg[v['condition']] = [int(v['price'])]
avg = {k: sum(v)/len(v) for k, v in avg.items()}
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.