Help in sorting dictionary

Hi there i will like to sort my dictionary by value and then by key. How do I do that? I manage to sort my dictionary by value according to the greatest number but I am unable to sort my dictionary by key after sorting the dictionary by value. Below are my output.

{'s': 7, 'd': 7, 't': 6, 'j': 4, 'v': 3}

Based on the output, I want to output according to alphabetical order if it has the same value. Below are my example

{‘d’: 7, ‘s’: 7, ‘t’: 6, ‘j’: 4, ‘v’: 3}

My code to sort the dictionary:

dict = sorted(dict.items(), key=lambda x: x[1], reverse=True)

I don’t see the problem, dict.items() gives back:

dict_items([('s', 7), ('d', 7), ('t', 6), ('j', 4), ('v', 3)])

so within your lambda function, doing x[1] will select the values while doing x[0] would sort by keys. You where so close?

I wanted to sort by value descending and when it is the same value, I want to sort the key in accessing order. I manage to sort it by value but not sorting the key by descending.

Desired Output:

{‘d’: 7, ‘s’: 7, ‘t’: 6, ‘j’: 4, ‘v’: 3}

Output I have:

{‘s’: 7, ‘d’: 7, ‘t’: 6, ‘j’: 4, ‘v’: 3}

The python documentation has a section on such a complex sorting:

https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts

With roughly the same scenario as you have

2 Likes

The desired output that you specified is a dictionary. Are you asking to sort the dictionary itself, or would it suffice to sort the contents of the dictionary and place the result into a tuple or a list?

If you need to have the dictionary itself sorted, you could save its contents into some other type of object, such as a list, sort the list, then rebuild the dictionary from the list. This is because in the most recent versions of Python, items in dictionaries are stored in the order in which they are inserted. In earlier versions of Python, dictionaries are unordered. This makes it impossible to reliably maintain a sorted dictionary in those versions of Python.

1 Like

Thanks all for the reply.

I manage to figure out on how to solve the issue by using the following link.

1 Like

Thanks, @yolo123456789012, for getting back to us regarding how you resolved the problem. This, from the source you cited, looks good:

sorted(d.items(), key=lambda x: (-x[1], x[0]))