Skip to content

Sort List of Dictionaries by Value in Python? Vijetha Spark By {Examples}

  • by

We can sort a list of dictionaries by value using sorted() or sort() function in Python. Sorting is always a useful utility in everyday programming. Using sorted() function we can sort a list of dictionaries by value in ascending order or descending order. This function sorts iterable objects like lists, tuples, sets, and dictionaries.

In this article, I will explain how to sort a list of dictionaries by value in ascending/descending order using Pyhton sorted() function and this function is also used to sort dictionary by value and sort dictionary by Key in Python.

1. Quick Examples of Sort a List of Dictionaries by Value

If you are in a hurry, below are some quick examples of how to sort a list of dictionaries by value.

# Below are some quick examples.

# Example 1: Sort list of dictionaries using sorted() & lambda
print(sorted(dict_list, key=lambda x: x[‘fruit_name’]))

# Example 2: Sort list of dictionaries in descending order
# using sorted()
print(sorted(dict_list, key=lambda x: x[‘fruit_name’], reverse = True))

# Example 3: Sort list of dictionaries when key doesn’t exist
print(sorted(dict_list, key=lambda x: x[‘calories’]))

# Example 4: Sort list of dictionaries using sorted() & get()
print(sorted(dict_list, key=lambda x: x.get(‘calories’)))

# Example 5: Sort list of dictionaries using sorted() & get()
# when key doesn’t exist
print(sorted(dict_list, key=lambda x: x.get(‘calories’, 95)))

# Example 6: Set operator.itemgetter() as key and sort
# list of dictionaries using sorted()
import operator
print(sorted(dict_list, key=operator.itemgetter(‘fruit_name’)))

# Example 7: Sort list of dictionaries without key existence
# using operator module
print(sorted(dict_list, key=operator.itemgetter(‘calories’)))

# Example 8: Sort a list of dictionaries having the same value for multiple keys
print(sorted(dict_list, key=operator.itemgetter(‘calories’)))

2. What is Python Dictionary

A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.

Let’s create a list of dictionaries,

# Create a list of dictionaries
dict_list = [{‘fruit_name’:’pomegranate’, ‘no.of alphabets’:11, ‘calories’:11},
{‘fruit_name’:’kiwi’, ‘no.of alphabets’:4, ‘calories’:42},
{‘fruit_name’:’Apple’, ‘no.of alphabets’:5},
{‘fruit_name’:’strawberry’, ‘no.of alphabets’: 10, ‘calories’:17}]
print(dict_list)

Yields below output.

3. Sort List of Dictionaries using sorted() & Lambda Functions

Python sorted() function can be used to sort the list of dictionaries in an ascending/descending order. When we sort the list of dictionaries using the sorted() or sort() function without specifying key parameter, by default TypeError raises.

To sort list of dictionaries by value using sorted() function we need to specify the key Parameter.

Let’s sort the list of dictionaries using the sorted() function and lambda function. In this example, I will specify the key parameter with fruit_name. This syntax will sort the given list of dictionaries by value according to ‘fruit_name’.

# Sort list of dictionaries using sorted() & lambda
# according to ‘fruit_name’
print(sorted(dict_list, key=lambda x: x[‘fruit_name’]))

Yields below output.

Let’s see another example of the list of dictionaries using sorted() function.

# Sort list of dictionaries using sorted() & lambda
# according to ‘no.of alphabets’
print(sorted(dict_list, key=lambda x: x[‘no.of alphabets’]))

# Output:
# [{‘fruit_name’: ‘kiwi’, ‘no.of alphabets’: 4, ‘calories’: 42}, {‘fruit_name’: ‘Apple’, ‘no.of alphabets’: 5},
# {‘fruit_name’: ‘strawberry’, ‘no.of alphabets’: 10, ‘calories’: 17}, {‘fruit_name’: ‘pomegranate’, ‘no.of
# alphabets’: 11, ‘calories’: 11}]

4. Sort List of Dictionaries in Descending Order in Python

Let’s use the sorted() function to sort the list of dictionaries in descending order. For that, we need to set the reverse param of the sorted() function as True and pass it into this function. It will sort the list of dictionaries by value with a specified key param in descending order.

# Sort list of dictionaries in descending order
# using sorted()
print(sorted(dict_list, key=lambda x: x[‘fruit_name’], reverse = True))

# Output:
# [{‘fruit_name’: ‘strawberry’, ‘no.of alphabets’: 10, ‘calories’: 17}, {‘fruit_name’: ‘pomegranate’, ‘no.of
# alphabets’: 11, ‘calories’: 11}, {‘fruit_name’: ‘kiwi’, ‘no.of alphabets’: 4, ‘calories’: 42}, {‘fruit_name’: # ‘Apple’, ‘no.of alphabets’: 5}]

So far, we have learned how to sort the list of dictionaries using the sorted() method. Similarly, we can also sort the list of dictionaries using the sort() function by specifying the key and reverse param. Only the difference between the sort() and sorted() function is sort() method sorts existing objects and sorted() method generates a new sorted object.

5. Sort List of Python Dictionaries When Specified Key does not Exist

When we use the sorted() method to sort the list of dictionaries by value with a specified key, which does not exist in the dictionary. It will raise the KeyError.

# Sort list of dictionaries when key doesn’t exist
print(sorted(dict_list, key=lambda x: x[‘calories’]))

# Output:
# KeyError

Alternatively, we can use the Python dictionary get() method, which returns the default value None for every non-existing key. None, which is not comparable to a number or a string, so an error raises.

# Sort list of dictionaries using sorted() & get()
print(sorted(dict_list, key=lambda x: x.get(‘calories’)))

# Output:
# TypeError: ‘<‘ not supported between instances of ‘NoneType’ and ‘int’

To overcome TypeError we can specify the value whose key doesn’t exist in the dictionary and pass it as a second param of get() method. It will sort the list of dictionaries when the key doesn’t exist in the dictionary.

# Sort list of dictionaries using sorted() & get()
# when key doesn’t exist
print(sorted(dict_list, key=lambda x: x.get(‘calories’, 95)))

# Output:
# [{‘fruit_name’: ‘pomegranate’, ‘no.of alphabets’: 11, ‘calories’: 11}, {‘fruit_name’: ‘strawberry’, ‘no.of
# alphabets’: 10, ‘calories’: 17}, {‘fruit_name’: ‘kiwi’, ‘no.of alphabets’: 4, ‘calories’: 42}, {‘fruit_name’:
# ‘Apple’, ‘no.of alphabets’: 5}]

As we can see from the above, The list has been sorted according to ‘calories’.

6. Sort using Set operator.itemgetter() as key parameter

Set operator.itemgetter() as a key parameter of sorted() function to sort the list of dictionaries by value with a specified key. itemgetter() is an operator module of the standard library. It can sort faster than using a lambda expression.

Sort a list of dictionaries by value according to the ‘fruit_name’ key.

# Set operator.itemgetter() as key and sort
# list of dictionaries using sorted()
import operator
print(sorted(dict_list, key=operator.itemgetter(‘fruit_name’)))

# Output:
# [{‘fruit_name’: ‘Apple’, ‘no.of alphabets’: 5}, {‘fruit_name’: ‘kiwi’, ‘no.of alphabets’: 4, ‘calories’: 42}, # {‘fruit_name’: ‘pomegranate’, ‘no.of alphabets’: 11, ‘calories’: 11}, {‘fruit_name’: ‘strawberry’, ‘no.of
# alphabets’: 10, ‘calories’: 17}]

7. Sort Descending order using Set operator.itemgetter()

Set reverse param as True and pass it into sorted() method along with itemgetter(), it will sort the list of dictionaries in descending order.

# Sort list of dictionaries in descending order
# using itemgetter()
import operator
print(sorted(dict_list, key=operator.itemgetter(‘fruit_name’), reverse = True))

# Output:
# [{‘fruit_name’: ‘strawberry’, ‘no.of alphabets’: 10, ‘calories’: 17}, {‘fruit_name’: ‘pomegranate’, ‘no.of
# alphabets’: 11, ‘calories’: 11}, {‘fruit_name’: ‘kiwi’, ‘no.of alphabets’: 4, ‘calories’: 42}, {‘fruit_name’:
# ‘Apple’, ‘no.of alphabets’: 5}]

When we sort the list of dictionaries by value without key occurrence using the operator module, KeyError will raise.

# Sort list of dictionaries without key existence
# using operator module
print(sorted(dict_list, key=operator.itemgetter(‘calories’)))

# Output:
# KeyError

8. Sort List of Python Dictionaries having Same Value for Multiple Keys

When we sort the list of dictionaries having the same value for multiple keys using sorted() function, it will sort the list of dictionaries and preserve the existing order. Let’s take an example,

# Create dictionary
dict_list = [{‘fruit_name’:’pomegranate’, ‘no.of alphabets’:11, ‘calories’:11},
{‘fruit_name’:’kiwi’, ‘no.of alphabets’:4, ‘calories’:42},
{‘fruit_name’:’Apple’, ‘no.of alphabets’:5, ‘calories’:17},
{‘fruit_name’:’strawberry’, ‘no.of alphabets’: 10, ‘calories’:17}]
print(dict_list)
import operator
# Sort a list of dictionaries having the same value for multiple keys
print(sorted(dict_list, key=operator.itemgetter(‘calories’)))

# Output:

# [{‘fruit_name’: ‘pomegranate’, ‘no.of alphabets’: 11, ‘calories’: 11}, {‘fruit_name’: ‘Apple’, ‘no.of alphabets’: 5, ‘calories’: 17}, {‘fruit_name’: ‘strawberry’, ‘no.of alphabets’: 10, ‘calories’: 17}, {‘fruit_name’: ‘kiwi’, ‘no.of alphabets’: 4, ‘calories’: 42}]

9. Conclusion

In this article, I have explained how to sort a list of dictionaries by value in ascending/descending order using Pyhton sorted(), sort(), lambda function, and itemgetter() functions with examples.

 We can sort a list of dictionaries by value using sorted() or sort() function in Python. Sorting is always a useful utility in everyday programming. Using sorted() function we can sort a list of dictionaries by value in ascending order or descending order. This function sorts iterable objects like lists, tuples, sets, and dictionaries. In  Read More Python, Python Tutorial, Python Dictionary Methods, Python Sorting 

Leave a Reply

Your email address will not be published. Required fields are marked *