Sort Dictionary in Python | Complete Guide
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This Python code demonstrates how to sort a dictionary by keys and values. The sorted() function is used to return a sorted list of tuples, which is then converted back to a dictionary.
- Sort by keys:
dict(sorted(my_dict.items())) - Sort by values: Using
key=lambda item: item[1] - Reverse sorting: Set
reverse=True
This is a common task in Python data manipulation, useful for ordered output.