Skip to content
Advertisement

dict(sorted(dictionary.items(), key=operator.itemgetter(1)) does not always return a ordered dict when the value is a list

I have a dict:

JavaScript

when I try to sort it by using

JavaScript

It not always sorts it like I want it to sort. (the value must have the biggest number and then descend) so it returns this:

JavaScript

everything is right except for that x should be in front of i since 4 > 3. Are some indexes more prioritized?

To facilitate the users , here is an Example of a well sorted list using the same code.

Before:

JavaScript

After:

JavaScript

Advertisement

Answer

When you compare lists, they’re compared lexicographically, so the first element takes precedence, then the second, and so on. If you want the largest list element to take precedence, compare sorted lists.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement