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.
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
for i in sorted(dict, key= lambda x: max(dict[x]), reverse=True):
print(i,max(dict[i]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With