How to sort a dictionary in python

how to sort a dictionary in python

In Python programming, dictionaries are useful data structures. They allow you to store key-value pairs. However, there might come a time when you need to  arrange the dictionary in particular order. Arranging a dictionary can be a bit tricky at first, but fear not!  In this guide, we’ll walk you through the process step by step.

What is a dictionary in python

A dictionary is a collection of key-value pairs, where each key is distinctive. The key is paired with a value. Dictionaries are defined using curly braces {}, and each key-value pair is separated by a colon :

For example

my_dict = {'b': 2, 'a': 1, 'c': 3}

In this dictionary, ‘b’, ‘a’, and ‘c’ are keys, and 2, 1, and 3 are their respective values.

How to sort a dictionary by key in python

An easy way to sort a dictionary is by its keys. Python provides the sorted() function, which allows you to sort a dictionary. Passing a dictionary to the sorted()  function sorts the dictionary key by default. Here’s how you can do it:

Considering the priority of fruits as value and key as fruit name. Writing code for sorting dictionary alphabetically.

Code

my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)

#output
#{'apple': 2, 'banana': 3, 'cherry': 1}

Code interpretation for sorting a dictionary by key in python

  • my_dict.items() returns a list of tuples showing key-value pairs from the dictionary my_dict.
  • The list of tuples is passed to the sorted() function which sorts key value pairs based on keys. 
  • Finally, dict() converts the sorted list of tuples back into a dictionary

How to sort a dictionary by value in python

Sorting the dictionary by value is somewhat difficult as compared to sorting by key.. However, you can get the task done by using the sorted() function with the custom sorting key. Here’s how you can do it:

Code

my_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_dict = {key: value for key, value in
sorted(my_dict.items(), key=lambda item: item[1])}
print(sorted_dict)

#output : {'a': 1, 'b': 2, 'c': 3}

Code interpretation for sorting a dictionary by value in python

  • my_dict.items(): This method returns a view object that shows a list of a dictionary’s key-value  as a list of tuples.
  • sorted(…): It sorts the key-value pairs returned by my_dict.items(). The key parameter is used in the sorted function for the basis of comparisons. Here, lambda item: item[1] specifies that the sorting should be done based on the values i.e the second element in each tuple.
  • {key: value for key, value in …}: Generating a dictionary through dictionary comprehension, it then traverses through a sorted list of key-value pairs.

How to sort a dictionary in python without sort function

While the sort function is a simple and efficient way to organize dictionaries in Python. There are other ways to sort a dictionary  without using the python inbuilt function.

Code

unsorted_dict={1:'jagdish',10:'mangesh',3:'rahul',2:'rishi'}

keys=list(unsorted_dict.keys())

#code for sorting a list
for i in range(len(keys)):
for j in range(0, len(keys)-i-1):
if keys[j] > keys[j+1]:
keys[j], keys[j+1] = keys[j+1], keys[j]

sorted_dict={key:unsorted_dict[key] for key in keys}
print(sorted_dict)


#output: {1: 'jagdish', 2: 'rishi', 3: 'rahul', 10: 'mangesh'}

 

First we initialize the dictionary. Keys variable is storing a list of all keys of the dictionary. We sort these keys in the dictionary in ascending order. Based on sorted keys we create a dictionary using  dictionary comprehension.

Conclusion

The most common method for organizing a dictionary is using the sorted() function with the key argument. You can also learn list comprehension in python.

You can find the above code on GitHub.

2 thoughts on “How to sort a dictionary in python”

  1. Pingback: Solving typeerror: unhashable type: 'numpy.ndarray' in Python -

  2. Pingback: Solving the 'dict_keys' Object is Not Subscriptable Error in Python

Comments are closed.