Wednesday, January 15, 2025
HomeProgrammingHow to Sort Dictionaries in Python

How to Sort Dictionaries in Python

In Python, dictionaries can be sorted by key or value using built-in functions like sorted().

Sort by Key:
To sort a dictionary by key, use sorted() with the key parameter, which sorts the keys in ascending order by default.

Example:
python
my_dict = {‘b’: 3, ‘a’: 1, ‘c’: 2}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}
print(sorted_dict) # Output: {‘a’: 1, ‘b’: 3, ‘c’: 2}

See also  Add hover text without JavaScript like we hover on a user's profile using HTML and CSS.

Sort by Value:
To sort a dictionary by value, use sorted() and specify a key function that sorts based on dictionary values.

Example:
python
my_dict = {‘b’: 3, ‘a’: 1, ‘c’: 2}
sorted_by_value = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}
print(sorted_by_value) # Output: {‘a’: 1, ‘c’: 2, ‘b’: 3}

See also  How do I create tabulation spacing in HTML?

Descending Order:
For descending order, add the reverse=True argument in sorted().

Sorting dictionaries allows for better data organization and retrieval based on keys or values

Previous article
Next article
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x