Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count all dictionary values by specific key and specific another dictionary value Python

I have this code:

base = [
    {'num': 10, 'bet': '100EUR'},
    {'num': 22, 'bet': '10EUR'},
    {'num': 10, 'bet': '210EUR'},
    {'num': 11, 'bet': '100EUR'},
    {'num': 8, 'bet': '50EUR'},
    {'num': 10, 'bet': '10EUR'},
    {'num': 8, 'bet': '30EUR'},
    {'num': 32, 'bet': '10EUR'}]

newbase = [{'num': b['num'], 'bet': int(b['bet'][:-3])}for b in base]
print(newbase)

There are duplicated values for dict ‘num’ in base. newbase = [{'num': b['num'], 'bet': int(b['bet'][:-3])}for b in base] deletes last 3 letter, so to be able to convert it to number. I have to make a program, that counts for each number how is sum of its money, and show 3 numbers with most money in them. For example output have to be like that:

10 = 320 EUR
11 = 100 EUR
8 = 80 EUR

How to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m always looking to practice my Python, so here’s what I came up with.

import itertools

base = [
    {'num': 10, 'bet': '100EUR'},
    {'num': 22, 'bet': '10EUR'},
    {'num': 10, 'bet': '210EUR'},
    {'num': 11, 'bet': '100EUR'},
    {'num': 8, 'bet': '50EUR'},
    {'num': 10, 'bet': '10EUR'},
    {'num': 8, 'bet': '30EUR'},
    {'num': 32, 'bet': '10EUR'}]

# Sort by "num"
base.sort(key=lambda x:x['num'])

# Use groupby to create a list of tuples
# Where index 0 is "num" and index 1 is sum of bet
temp = []
for k,v in itertools.groupby(base, key=lambda x:x['num']):
    temp.append((k, sum(int(x['bet'][:-3]) for x in v)))

# Sort the tuples on bet
temp.sort(key=lambda x:x[1], reverse=True)

for i in range(3):
    print(f"{temp[i][0]} = {temp[i][1]} EUR")

Output:

10 = 320 EUR
11 = 100 EUR
8 = 80 EUR
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading