Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 508
D3107 Avatar asked Jan 06 '23 18:01

D3107


2 Answers

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
like image 139
timgeb Avatar answered Jan 15 '23 08:01

timgeb


for i in sorted(dict, key= lambda x: max(dict[x]), reverse=True):
    print(i,max(dict[i]))
like image 26
goCards Avatar answered Jan 15 '23 08:01

goCards