8 simple ways to sort dictionary by value in Python


Python

We have already learned about Python Dictionary. In this article I will share different methods in Python to sort dictionary by value field. Some of these methods can also be tweaked so sort the dictionary items by keys. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. Although you need to continue to use OrderedDict if you want insertion ordering that's guaranteed across older implementations of Python.

I will be using Python 3.6 for verifying all the example scripts from this tutorial so if you are on older Python version such as 2.X then test individual examples to make sure they are working in your environment.

]# python3 -V
Python 3.6.8

 

Method-1: Sort dictionary by value using for loop with sorted()

This is a very basic example which should work on older releases of Python as well. Here we sort the values of the dictionary and store it in a variable then use for loop to map the key and value and then store the sorted item content in new dictionary variable.

#!/usr/bin/env python3

mydict_1 = {'Fruit': 'Mango', 'Vegetable': 'Potato', 'Car': 'Swift', 'Bike': 'Hornet'}

# Create new dictionary for output with sorted value
new_dict = {}

# sort the values and store them in a new variable
sorted_value = sorted(mydict_1.values())

# for all the values in sorted_value
for i in sorted_value:
   # match the value with un sorted dictionary
   for key, value in mydict_1.items():
       if value == i:
          # when matched place the key and value in the new dict
           new_dict[key] = value

print(new_dict)

Output from this script. As you can see the new dictionary contains the key value pairs where value are sorted:

8 simple ways to sort dictionary by value in Python

 

Method-2: Sort dictionary by value using sorted() with lambda

In this example we will use sorted() function with lambda to sort the dictionary items based on value i.e. item[1]. Ideally using this method the output would be in list type so I am using additional dict() function to convert the output into dictionary type. A lambda is an anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [parameters]: expression

#!/usr/bin/env python3

mydict = {'Fruit': 'Mango', 'Vegetable': 'Potato', 'Car': 'Swift', 'Bike': 'Hornet'}

print('Without sort: ', mydict)

sorted_mydict = dict(sorted(mydict.items(), key=lambda item: item[1]))
print('After sort: ', sorted_mydict)

print(type(sorted_mydict))

The output is again in sorted format based on dictionary value:

8 simple ways to sort dictionary by value in Python

 

Method-3: Sort dictionary by value using for loop with sorted() and lambda

In this example we are using for loop to iterate over individual dictionary items and then storing the sorted items in a different dictionary. This code also uses lambda with sorted().

#!/usr/bin/env python3

mydict = {'Fruit': 'Mango', 'Vegetable': 'Potato', 'Car': 'Swift', 'Bike': 'Hornet'}
# Empty dictionary to store the sorted items
new_dict = {}

print('Without sort: ', mydict)

# This will sort the dictionary by the values of each entry
# within the dictionary from smallest to largest
for key, value in sorted(mydict.items(), key=lambda item: item[1]):
    # store the sorted items in new dictionary
    new_dict[key] = value

print(new_dict)
print(type(new_dict))

Output:

8 simple ways to sort dictionary by value in Python

 

Method-4: Sort dictionary by value using itemgetter()

The itemgetter() is part of operator module which returns a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values.

#!/usr/bin/env python3

import operator

mydict = {'Fruit': 'Mango', 'Vegetable': 'Potato', 'Car': 'Swift', 'Bike': 'Hornet'}

print('Without sort: ', mydict)

# sort dictionary values using itemgetter(1)
sorted_mydict = dict(sorted(mydict.items(), key=operator.itemgetter(1)))
print('After sort: ', sorted_mydict)

print(type(sorted_mydict))

Output:

8 simple ways to sort dictionary by value in Python

 

Method-5: Sort dictionary by value using OrderedDict with itemgetter()

For users with older Python versions such as 2.X you will have to use OrderedDict to sort the items as shown in Method-4.

~]# python2 -V
Python 2.7.5
#!/usr/bin/env python2

from operator import itemgetter
from collections import OrderedDict

mydict = {'Fruit': 'Mango', 'Vegetable': 'Potato', 'Car': 'Swift', 'Bike': 'Hornet'}

print('Without sort: ', mydict)

# sort dictionary values using itemgetter(1)
sorted_mydict = OrderedDict(sorted(mydict.items(), key=itemgetter(1)))
print('After sort: ', sorted_mydict)

print(type(sorted_mydict))

Output:

8 simple ways to sort dictionary by value in Python

 

Method-6: Sort dictionary by value using sorted() with zip()

We can use sorted() to sort the dictionary keys and values individually and later zip will make an iterator that aggregates elements from each of the iterables. Now zip() returns an iterator of tuples so we use dict() to convert it to dictionary type.

#!/usr/bin/env python3

mydict = {'Fruit': 'Mango', 'Vegetable': 'Potato', 'Car': 'Swift', 'Bike': 'Hornet'}

print('Without sort: ', mydict)

# create (value, key) pairs using zip()
sorted_mydict = dict(sorted(zip(mydict.values(), mydict.keys())))
print('After sort: ', sorted_mydict)

print(type(sorted_mydict))

Output

8 simple ways to sort dictionary by value in Python

 

Method-7: Sort dictionary by value using sorted() with get()

We have already used sorted() function a couple of times, now in this example we will again use sorted() with get() method in this format: sorted(dict, key=dict.get). The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value.

So key=dict.get will list the dictionary keys and we will sort the output using sorted(). Next using for loop we map the keys and values from the original dictionary and store the item pair in new dictionary.

#!/usr/bin/env python3

mydict = {'Fruit': 'Mango', 'Vegetable': 'Potato', 'Car': 'Swift', 'Bike': 'Hornet'}
new_dict = {}

print('Without sort: ', mydict)

# sort dictionary keys using sorted()
sorted_keys = sorted(mydict, key=mydict.get)

# map the sorted keys with values from original dictionary
for word in sorted_keys:
    new_dict[word] = mydict[word]

print('After sort: ', new_dict)
print(type(new_dict))

Output

8 simple ways to sort dictionary by value in Python

 

Method-8: Sort dictionary by value using Counter

A Counter is part of collections module and is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.

Starting with Python 3.7, As a dict subclass, Counter Inherited the capability to remember insertion order. Math operations on Counter objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand.

#!/usr/bin/env python3

from collections import Counter

mydict = {'a':5, 'b':3, 'c':7}
print('Without sort: ', mydict)

new_dict = Counter(mydict)
print('After sort', dict(new_dict.most_common()))

Output:

8 simple ways to sort dictionary by value in Python

 

Summary

Starting with Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted and the same was confirmed with Python 3.7 as it becomes a language feature. So there are a number of ways we can sort a Dictionary item (both key and value). But if you are still on older version of Python then you should use OrderedDict() from collections module to insert items in order.

Deepak Prasad

Deepak Prasad

Deepak Prasad is the founder of GoLinuxCloud, bringing over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, Networking, and Security. His extensive experience spans development, DevOps, networking, and security, ensuring robust and efficient solutions for diverse projects.

Certifications and Credentials:

  • Certified Kubernetes Application Developer (CKAD)
  • Go Developer Certification
  • Linux Foundation Certified System Administrator (LFCS)
  • Certified Ethical Hacker (CEH)
  • Python Institute PCAP (Certified Associate in Python Programming)
You can connect with him on his LinkedIn profile and join his Facebook and LinkedIn page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment