How to Sort List of Dictionaries in Python

Home /

Table of Contents

Sorting a list of dictionaries by a value

In Python, you can sort a list of dictionaries by a value using the ‘sorted‘ function and providing a ‘key‘ function that returns the value to sort by. For example, consider the following list of dictionaries:

Python
list_of_dicts = [{"name": "John", "age": 28},                
 {"name": "Jane", "age": 31},                
 {"name": "Jim", "age": 25}]

To sort this list of dictionaries by the "age" key, you can do the following:

Python
sorted_list_of_dicts = sorted(list_of_dicts, key=lambda x: x["age"])

This will return a new list of dictionaries sorted by the value of the "age" key in ascending order. To sort in descending order, you can use the ‘reverse‘ argument:

Python
sorted_list_of_dicts = sorted(list_of_dicts, key=lambda x: x["age"], reverse=True)

The above code will return a new list of dictionaries sorted by the value of the "age" key in descending order.

Add Keys and Sort in a Loop in Dictionary

To add values to a dictionary and sort the dictionary by values in a loop, you can use the built-in ‘sorted()function along with a lambda function to specify the sorting key. Here’s an example:

Python
# Initialize an empty dictionary
my_dict = {}

# Loop to add values to the dictionary
while True:
    # Get user input for key and value
    key = input("Enter a key (or 'quit' to exit): ")
    if key == 'quit':
        break
    value = int(input("Enter a value: "))
    
    # Add the key-value pair to the dictionary
    my_dict[key] = value
    
    # Sort the dictionary by values and print the result
    sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
    print(sorted_dict)

In this example, we start with an empty dictionary ‘my_dict‘. We then use a ‘while‘ loop to repeatedly ask the user for a key-value pair to add to the dictionary. If the user enters 'quit', the loop breaks and the program ends. Otherwise, the program adds the key-value pair to the dictionary using the square bracket notation.

After each key-value pair is added to the dictionary, the program uses the ‘sorted()‘ function to sort the dictionary by values, using a lambda function to specify the sorting key. The lambda function takes an item (i.e., a key-value pair) and returns the value of the item, which is used for sorting. The result of ‘sorted()‘ is a list of tuples, where each tuple contains a key-value pair from the dictionary, sorted by value.

We then use the ‘dict()‘ function to convert the sorted list of tuples back to a dictionary, and assign it to ‘sorted_dict‘. Finally, we print ‘sorted_dict‘ using the ‘print()‘ function.

Note that this code will sort the dictionary after each key-value pair is added, so the order of the dictionary may change with each iteration of the loop. If you want to sort the dictionary only once, after all key-value pairs have been added, you can move the sorting code outside the loop.

Sort a Dictionary in Reverse order

To sort a dictionary in reverse order, you can use the ‘sorted()‘ function with the ‘reverse=True‘ parameter. Here’s an example:

Python
# Create a dictionary
my_dict = {'Alice': 25, 'Bob': 30, 'Charlie': 35, 'Dave': 40}

# Sort the dictionary in reverse order
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))

# Print the sorted dictionary
print(sorted_dict)

In this example, we start with a dictionary ‘my_dict‘ that contains four key-value pairs. We then use the ‘sorted()‘ function to sort the dictionary by values in reverse order, using a lambda function to specify the sorting key. The ‘reverse=True‘ parameter tells the ‘sorted()‘ function to sort in reverse order.

We then use the ‘dict()‘ function to convert the sorted list of tuples back to a dictionary, and assign it to ‘sorted_dict‘. Finally, we print ‘sorted_dict‘ using the ‘print()‘ function. The output of this code will be:

{'Dave': 40, 'Charlie': 35, 'Bob': 30, 'Alice': 25}

As you can see, the dictionary is sorted in reverse order by values, with the key-value pair 'Dave': 40' appearing first and the key-value pair 'Alice': 25' appearing last.

Share The Blog With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit
Other Recommended Article