Timothy Lombard
Timothy Lombard

Reputation: 967

iterate thru dict ordered by descending summed values

My dictionary looks like this...

   d = {'clovato': [2.0, 1.0, 1.0, 1.5, 2.0], 'fnegro': [1.0, 3.0, 0.5], 'jbgood': [4.0, 4.0, 1.5, 1.5]}

So while I can calculate the sum of each key's value

for k,v in d.items():
    print(k,sum(v))

clovato 7.5
fnegro 4.5
jbgood 11.0 

What I really need is to have the key-value pairs print in descending order of the sum. In this case, I want the output to be:

jbgood, [4.0, 4.0, 1.5, 1.5]
clovato, [2.0, 1.0, 1.0, 1.5, 2.0]
fnegro, [1.0, 3.0, 0.5]

Upvotes: 0

Views: 32

Answers (2)

vash_the_stampede
vash_the_stampede

Reputation: 4606

Using comprehension with sorted x[0] and reverse

print(*sorted([[k, v] for k, v in d.items()], key=lambda x: sum(x[1]), reverse = True))
['jbgood', [4.0, 4.0, 1.5, 1.5]] ['clovato', [2.0, 1.0, 1.0, 1.5, 2.0]] ['fnegro', [1.0, 3.0, 0.5]]

Upvotes: 1

MooingRawr
MooingRawr

Reputation: 4981

Just use sorted and use the sum as the key, using reverse to make it ascending.

d = {'clovato': [2.0, 1.0, 1.0, 1.5, 2.0], 'fnegro': [1.0, 3.0, 0.5], 'jbgood': [4.0, 4.0, 1.5, 1.5]}

od = sorted(d.items(), key=lambda x: sum(x[1]),reverse=True)

for key,value in od:
    print(key, value)

Upvotes: 3

Related Questions