Basic Programs

If Else Programs

While loop Programs

For loop Programs

List Programs

Dict Programs


Python Program To Sort the Dictionaries by Values or Keys.


In this example shows, we will sort the dictionary by keys and values, the result will display the type of dictionary.

Sorting by Keys

Example.py
# Sample dictionary
info = {'ram': 22, 'sam': 27,'saraa': 19, 'mukesh': 16, 'karthi': 32}

# Sort dictionary by keys
sorted_by_keys = dict(sorted(info.items()))
print("Dictionary sorted by keys:", sorted_by_keys)
  • sorted(info.items()) : This sorts the dictionary items based on keys by default.
  • dict() : This converts the sorted items back into a dictionary.

Output

Dictionary sorted by keys: {'karthi': 32, 'mukesh': 16, 'ram': 22, 'sam': 27, 'saraa': 19}

Sorting by Values

Example.py
# Sample dictionary
info = {'ram': 22, 'sam': 27,'saraa': 19, 'mukesh': 16, 'karthi': 32}

# Sort dictionary by values
sorted_by_values = dict(sorted(info.items(), key=lambda item: item[1]))
print("Dictionary sorted by values:", sorted_by_values)
  • sorted(info.items(), key=lambda item: item[1]) : This sorts the dictionary based on values. The lambda item: item[1] part tells Python to use the values (not the keys) for sorting.
  • dict() : This converts the sorted list of tuples back into a dictionary.

Output

Dictionary sorted by values: {'mukesh': 16, 'saraa': 19, 'ram': 22, 'sam': 27, 'karthi': 32}

Prev Next