Python Dictionary Sorting (By Key / By Value)
Page Info
Content
Python Dictionary Sorting (By Key / By Value)
In Python, dictionaries can be sorted by their keys or values using the sorted()
function. This allows you to organize dictionary items efficiently for display or processing.
Sorting by Keys
# Sample dictionary
my_dict = {'apple': 5, 'banana': 2, 'cherry': 7}
# Sort dictionary by keys
sorted_by_keys = dict(sorted(my_dict.items()))
print(sorted_by_keys)
# Output: {'apple': 5, 'banana': 2, 'cherry': 7}
Explanation:
my_dict.items()
returns key-value pairs.sorted(...)
sorts the pairs by key by default.- Convert back to
dict()
to get a sorted dictionary.
Sorting by Values
# Sort dictionary by values
sorted_by_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_by_values)
# Output: {'banana': 2, 'apple': 5, 'cherry': 7}
Explanation:
key=lambda item: item[1]
tellssorted()
to use dictionary values for sorting.- Convert the sorted items back to
dict()
to create a dictionary with sorted values.
Sorting in Descending Order
# Sort by keys descending
sorted_keys_desc = dict(sorted(my_dict.items(), reverse=True))
print(sorted_keys_desc)
# Output: {'cherry': 7, 'banana': 2, 'apple': 5}
# Sort by values descending
sorted_values_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_values_desc)
# Output: {'cherry': 7, 'apple': 5, 'banana': 2}
Key Points
- sorted(): Can sort any iterable including dictionary items.
- Sorting by key: Default behavior of
sorted()
. - Sorting by value: Use
key=lambda item: item[1]
. - Descending order: Add
reverse=True
tosorted()
.
SEO Keywords
Python dictionary sort, sort dict by key, sort dict by value, Python dict descending, Python sorted dictionary, Python lambda dict sort
These methods allow you to sort Python dictionaries efficiently by keys or values, in ascending or descending order, for better data management and display.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.