Sorting a Dictionary

tags: #python/documentation/dictionaries

Sorting by Values

1. Sorting using values() Method

We can sort a dictionary by its keys using the values() method with the sorted() function:

sorted_d = sorted(d.values())

2. Alternative Sorting Using Lambda

We can also use lambda functions to create custom sorting key:

sorted_d = sorted(d.items(), key=<lambda_expression>)

Example:

my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}

When you use my_dict.items(), it returns a view of the dictionary as a list of key-value pairs (tuples). For this dictionary, my_dict.items() would be:

[('apple', 5), ('banana', 2), ('orange', 8), ('grape', 1)]

Using the following lambda function, it will take an item, which is a key-value pair represented as a tuple. The lambda function extracts the second element of the tuple (item[1]), which is the value associated with the key. In this case, it takes the value from each tuple and will sorted by its value.

lambda item: item[1] # each item in the iterable will be passed
sorted_pairs = sorted(my_dict.items(), key=lambda item: item[1])
[('grape', 1), ('banana', 2), ('apple', 5), ('orange', 8)]

As the sorted() returns a new sorted list, we can pass the object back in the dict() constructor function to get a dictionary:

sorted_dict = = dict(sorted_pairs)
{'grape': 1, 'banana': 2, 'apple': 5, 'orange': 8}

Sorting by Keys

1. Sorting using keys() Method

We can sort a dictionary by its keys using the keys() method with the sorted() function:

sorted_d = sorted(d.keys())

2. Sorting Using items()

We can can sort a dictionary by using the items() method which returns a tuple of the key-value pair in a list. When used with the sorted() function, this automatically sorts by the key without specifying.

sorted_d = sorted(d.items())

3. Alternative Sorting Using Lambda

my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}

# Sorting the dictionary by keys in ascending order
sorted_dict_keys = dict(sorted(my_dict.items(), key=lambda item: item[0]))
Powered by Forestry.md