Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting a dictionary of pairs based on value

I have the code

mydict = {"layer1" : { 0: 0.765}, 'layer2': {0: 0.9876}}
for idx in range(5):
   mydict['layer1'][idx] = idx + 900
   mydict['layer2'][idx] = idx + 800
sorted_x = sorted(mydict.items(), key=lambda kv: kv[1])

it gives the error

TypeError: ‘<‘ not supported between instances of ‘dict’ and ‘dict’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

when I type

sorted_x = sorted(mydict.items(), key=lambda kv: kv[2])

it gives the error

IndexError: tuple index out of range

it onley works for index 0 which is a string!

I want the dictionary to be sorted based on the value and give the results like

[(‘layer2’, {0: 800, 1: 801, 2: 802, 3: 803, 4: 804}), (‘layer1’, {0: 900, 1: 901, 2: 902, 3: 903, 4: 904})]

what should I do?

>Solution :

Here is a simple change you can put in your code:

Change

sorted_x = sorted(mydict.items(), key=lambda kv: kv[1])

to:

sorted_x = sorted(mydict.items(), key=lambda kv: kv[1][1])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading