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:

count2:defaultdict(<class 'list'>, {'i': [3, 2, 2, 1], 'w': [2, 2], 'p': [2, 2], 'd': [2, 2], 'm': [2, 2], 'y': [2, 2, 2, 1], 'x': [2, 2, 4, 1], 'j': [2, 2], 'o': [2, 1], 'r': [2, 1]})

when I try to sort it by using

ordered = dict(sorted(count2.items(), key=operator.itemgetter(1), reverse=True)) 

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:

orderedStart:{'i': [3, 2, 2, 1], 'x': [2, 2, 4, 1], 'y': [2, 2, 2, 1], 'w': [2, 2], 'p': [2, 2], 'd': [2, 2], 'm': [2, 2], 'j': [2, 2], 'o': [2, 1], 'r': [2, 1]}

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:

count2:defaultdict(<class 'list'>, {'r': [2, 2, 2, 1], 'g': [2, 1], 'e': [3, 1], 'n': [5, 1], 't': [4, 1], 'i': [2, 1], 'o': [5, 1], 'm': [2, 1]})

After:

{'n': [5, 1], 'o': [5, 1], 't': [4, 1], 'e': [3, 1], 'r': [2, 2, 2, 1], 'g': [2, 1], 'i': [2, 1], 'm': [2, 1]}

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.

ordered = dict(sorted(count2.items(), key=lambda item: sorted(item[1], reverse=True), reverse=True)) 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement