[英]A Pythonic way to “query” a dictionary
我有一個嵌套字典,其中包含有關書籍的數據:
這是定義:
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'}
}
我需要得到平均價格,按條件分組。 所以,預期的結果是:
{'fair': 70, 'good': 100, 'excellent': 165}
什么是最恐怖的方式呢?
使用collections.defaultdict
演示:
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() })
輸出:
{'good': 100, 'fair': 70, 'excellent': 165}
我想用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()
輸出:
condition
excellent 165
fair 70
good 100
這是一種方法:
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}
除了不使用Try Except
之外,我不明白為什么你需要defaultdict
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()}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.