简体   繁体   English

Pythonic“查询”字典的方法

[英]A Pythonic way to “query” a dictionary

I have a nested dictionary which contains the data about books: 我有一个嵌套字典,其中包含有关书籍的数据:

  • UID UID
  • Condition 条件
  • Price 价钱

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 使用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. 我想用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 - 除了不使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM