D3107
D3107

Reputation: 161

Sorting a dictionary by highest value of nested list

dict = {a:[2, 4, 5], b:[4, 6, 7], c:[3, 1, 1]}

Using the above as an example, how would I sort and print this dict so It displayed as :

>>>sorthighest(dict)
b : 7
a : 5
c : 3

I'm pretty sure the way to go about this is by doing something along the lines of max(dict[i]) in a for: loop but I can't get anything to work.

Upvotes: 4

Views: 390

Answers (3)

timgeb
timgeb

Reputation: 78790

Don't use the name dict, it will shadow the builtin dictionary. You can create a dictionary mapping your orignal keys to the maximum value of the sublists:

>>> d_max = {k:max(d[k]) for k in d}
>>> d_max
{'a': 5, 'c': 3, 'b': 7}

And then iterate over the sorted items of that dictionary:

>>> for k, v in sorted(d_max.items(), key=lambda x: x[1], reverse=True):
...     print('{} : {}'.format(k,v))
... 
b : 7
a : 5
c : 3

edit: If you never need the d_max dictionary in order to look up the max values, we can simplify a little further:

>>> for k,v in sorted(((max(d[k]), k) for k in d), reverse=True): 
...     print('{} : {}'.format(v,k))
... 
b : 7
a : 5
c : 3

Upvotes: 4

gtlambert
gtlambert

Reputation: 11971

Dictionaries are unordered. To create an ordered dictionary use collections.OrderedDict as follows:

from collections import OrderedDict

d = {'a': [2,4,5], 'b': [4,6,7], 'c': [3,1,1]}
modified = {k: max(v) for k, v in d.items()}
answer = OrderedDict(sorted(modified.items(), key=lambda x: x[1], reverse=True))
print(answer)

Output

OrderedDict([('b', 7), ('a', 5), ('c', 3)])

You can then easily iterate over your ordered dictionary as follows:

for k, v in answer.items():
    print('{} : {}'.format(k, v))

Output

b : 7
a : 5
c : 3

Upvotes: 2

goCards
goCards

Reputation: 1436

for i in sorted(dict, key= lambda x: max(dict[x]), reverse=True):
    print(i,max(dict[i]))

Upvotes: 2

Related Questions