Sorting a dictionary by the highest value of a nested list

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

Using the above example, how would I sort and print this dict so that it displays as:

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

I am sure that this can be done by doing something in the lines max(dict[i])in a loop for:, but I cannot get something to work.

+4
source share
4 answers

Do not use the name dict, it obscures the built-in dictionary. You can create a dictionary matching your orignal keys with the maximum subscription value:

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

And then iterate over the sorted elements of this 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: d_max , :

>>> 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
+4
for i in sorted(dict, key= lambda x: max(dict[x]), reverse=True):
    print(i,max(dict[i]))
+2

Dictionaries are disordered. To create an ordered dictionary, use collections.OrderedDictas 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)

Exit

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

Then you can easily iterate over the ordered dictionary as follows:

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

Exit

b : 7
a : 5
c : 3
+2
source

EDIT: now it also returns keys.

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

It returns:

[('b', 7), ('a', 5), ('c', 3)]
+1
source

Source: https://habr.com/ru/post/1625648/


All Articles