CiaranWelsh
CiaranWelsh

Reputation: 7681

Summing values in nested dictionaries

I have a nested Python dictionary:

dct={1: {'13C': (13, 'C'), '6C': (6, 'C'), '13D': (13, 'D'), '10D': (10, 'D'), '7H': (7, 'H'), '5H': (5, 'H'), '5D': (5, 'D')}, 2: {'6C': (6, 'C'), '10D': (10, 'D'), '7H': (7, 'H'), '14D': (14, 'D'), '5H': (5, 'H'), '5D': (5, 'D'), '14C': (14, 'C')}}

I'm looking to extract the numbers only for each of the sub-dictionaries, determine the highest 5 numbers and then sum them. My code so far (and I've tried many variations as well as other suggestion for other similar posts in itertools):

    for player in dct:
        print player
        print dct[player]
        for cards in dct[player].keys():
            print cards

The desired outcome:

The entry '5D' and '5H' are the lowest (in this case) for the first and the second entries, therefore they would not be included in the sum. Therefore the outcome for the first entry first=13+6+13+10+7 and second=6+10+7+14+14. So first=49 and second=51. How to do this calculation?

Upvotes: 1

Views: 1507

Answers (5)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

if you want the n largest you can use nlargest:

from operator import itemgetter
from heapq import nlargest
n = 5

maxes = [(k, sum(nlargest(n, map(itemgetter(0), v.values())))) 
          for k, v  in dct.items()]

output:

[(1, 49), (2, 51)]

Or if you just want the sums:

maxes = [(sum(nlargest(n, map(itemgetter(0), v.values())))) 
          for v  in dct.values()]

Which would give you:

[49, 51]

Upvotes: 1

timgeb
timgeb

Reputation: 78690

I'd do it like this:

>>> {k:sum(sorted((x[0] for x in v.values()))[-5:]) for k,v in dct.items()}
{1: 49, 2: 51}

Upvotes: 0

Martin Konecny
Martin Konecny

Reputation: 59611

You can extract the numbers like so

numbers = [sum(sorted([y[0] for x, y in v.iteritems()])[-5:]) for k, v in dct.iteritems()]
print numbers  # [49, 51]

Upvotes: 0

poke
poke

Reputation: 387677

You want to iterate through all subdictionaries, and then extract the values. Find the five highest values, and sum those:

>>> for key, subdictionary in dct.items():
        values = [x[0] for x in subdictionary.values()]
        values.sort(reverse=True)
        print(key, sum(values[:5]))

1 49
2 51

Upvotes: 1

Csene
Csene

Reputation: 69

result = [sum(sorted([ int(x[:-1]) for x in dct[key]])[-5:]) for key in dct]

if you also need the keys:

result = [(key, sum(sorted([int(x[:-1]) for x in dct[key]])[-5:])) for key in dct]

Upvotes: 0

Related Questions