Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Pythonic way to "query" a dictionary

I have a nested dictionary which contains the data about books:

  • 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?

like image 270
Ildar Akhmetov Avatar asked Aug 04 '26 08:08

Ildar Akhmetov


2 Answers

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}
like image 146
Rakesh Avatar answered Aug 06 '26 23:08

Rakesh


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
like image 22
V Sree Harissh Avatar answered Aug 06 '26 21:08

V Sree Harissh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!