Don't let the Lockdown slow you Down - Enroll Now and Get 3 Course at 24,999/- Only. Explore Now!

General

How to Sort Python Dictionaries by Key or Value

How to Sort Python Dictionaries by Key or Value?

Python is a useful programming language used by most of the programmers. It holds different natural data types like tuple, set, dictionary, list, and more. It also consists of different kinds of modules that have data structures in a specialized way like Deque, Chain Map, and more. The data types include simple functions and therefore working with data type becomes more accessible, and this also makes the code efficient. The sort function is considered to be one active and essential function in a Python dictionary. In this tutorial, we will learn about sorting a dictionary in Python.

What do you mean by Dictionary?

Dictionary refers to the data type collection that includes the key-value pair similar to map in other types of programming languages. Here is a detailed explanation of what a dictionary is

  • Dictionary is unordered and enables duplicate entries, only in the values as the keys are considered to be different.
  • A dictionary is confessed in curly brackets.
  • Dictionary is uncertain in nature, and it means even after the dictionary in Python is declared, the changes can be made.
  • The values in the dictionary can be accessed with the help of keys as indexes in the dictionary.

Let’s check out the syntax for the dictionary.

mydictionary = { 'keya' : 'value a' , 'keyb' : 'value b' , 'keyc' : 'value c'}
print(mydictionary)

The output when executing the above format will be

{ 'keya' : 'value a' , 'keyb' : 'value b' , 'keyc' : 'value c'}

What is the different type of operations in the dictionary?

There are plenty of operations that can be performed on Python dictionaries, namely.

  • Clear
  • Fromkeys
  • Items
  • Popitem
  • Setdefault
  • Values
  • Copy
  • Get
  • Keys
  • Pop
  • Update

Why should you sort a dictionary?

There are numerous reasons to state why sorting a dictionary is essential. Some of them include

  • A sorted dictionary provides excellent clarity and understanding in dealing with the operations.
  • A dictionary includes 0(1) complexity of search time, in which the list has 0(n) complexity of search time, and this makes the dictionary a better option everywhere.
  • Sorting in the dictionary helps to make dynamic analysis while working with different data structures.

How can you sort a Python dictionary?

There are four steps followed for sorting a dictionary on Python namely.

Sorting by keys

The in-built sorted function can be used for sorting. This will take any type of iterable and then return back the list in a sorted way. Sorting by keys can be used to arrange the dictionary in the ascending order.

Let’s check the sorting by keys with an example.

x = {3:4, 4:3 ,6:5 ,5:6, 8:7,7:8}
#help to print the keys as a sorted list.
print(sorted(x.keys()))
#print the items in the sorted list
print(sorted(x.items()))

The output of the above code will be

[3,4,5,6,7,8]
[(3,4),(4,3),(5,6),(6,5),(7,8),(6,7)

Sorting by values:

This is also the same as sorting the key. Instead of a key, values can be used. Let’s check out an example.

x = {3:4, 4:3 ,6:5 ,5:6, 8:7,7:8 }
print(sorted.values()))
#this will print values in the sorted list

The output of the above code will be

Output:

[ 3,4,5,6,7,8]

Custom sorting algorithm using number and string.

We can make use of the arguments in the sorted method to perform the complex sortings. Let’s check this with an example.

day = { 'ab' : 'Monday' , 'cd' : 'Tuesday' , 'ef' : 'Wednesday' , 'gh' : 'Thursday' , 'ij': 'Friday' , 'kl' : 'Saturday' , 'mn': 'Sunday'}
print(day)
number = { 'ab' : 1 , 'cd' : 2 , 'ef' : 3 , 'gh' : 4 , 'ij' : 5 , 'kl' : 6 , 'mn' : 7}
print(sorted(day , key=number.__getitem__))
print([day[x] for x in sorted(day , key=number.__getitem__)])

The output of the above code will be

{ 'ab' : 'Monday' , 'cd' : 'Tuesday' , 'ef' : 'Wednesday' , 'gh' : 'Thursday' , 'ij': 'Friday' , 'kl' : 'Saturday' , 'mn': 'Sunday'}
['ab', 'cd' , 'ef' , 'gh' , 'ij' , 'kl' , 'mn']
['Monday' , 'Tuesday', 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' , 'Sunday' ]

We can also make use of different arguments for sorting the dictionary in the right way with the help of numbers and strings. Additionally, we can even reverse the same order and here is one of the examples to show the sorted dictionary in reverse order.

Reversing the sorted orders

Let me explain this with the example so that you can clearly understand how to reverse the sorted ones.

x = {3:4, 4:3 ,6:5 ,5:6, 8:7,7:8 }
print(sorted(x.values() , reverse= True))

The output of the above code will be

[8,7,6,5,4,3]

I hope the above tutorial helped you to know about sorting the dictionary in Python clearly. Do you have any queries on sorting a dictionary in Python? Let me know through the comment section below.

Related Blogs:

  1. Brief Overview of Python Language
  2. Python Career opportunities
  3. Python Break Continue
  4. Python Control Flow
  5. Python Data Types
  6. Python Dictionary
  7. Python Exception Handling
  8.  Python File
  9. Python Functions
  10. Python Substring
Scroll Up
Besant Technologies WhatsApp