2

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?

0

4 Answers 4

3

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}
1
  • 1
    Oh, defaultdict nails it! Thank you! Commented Aug 21, 2018 at 12:36
2

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
2
  • 3
    pandas seems like the most natural solution to this. Whenever I see one of the (relatively rare) situations where R is more elegant than Python for a certain type of problem, there is usually a pandas solution lurking around. Commented Aug 21, 2018 at 12:43
  • 1
    Yeah, pandas might be really useful. I have many more fields and potential queries for this dictionary, so creating and querying a dataframe sounds really promising. Commented Aug 21, 2018 at 12:45
2

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}
2
  • This assumes you already know the list of possible conditions. What if you don't?
    – user2261062
    Commented Aug 21, 2018 at 12:47
  • 1
    @SembeiNorimaki Then you have to do something much less elegant (if you want to use a direct dictionary comprehension). This limitation is one of the reasons I upvoted the pandas answer and was glad to see that it was accepted. Commented Aug 21, 2018 at 12:55
2

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()}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.