Understand How to Sort Dictionary by Value in Python

Last updated on Jun 19,2023 17K Views

Understand How to Sort Dictionary by Value in Python

edureka.co

Python is a high-level programming language that has been designed in C. It follows the object-oriented programming approach. Sorting a dictionary in Python by value is one of the many things one can do and in this article, I will teach how to Sort Dictionary by Value in Python.

 

Prerequisites: Sort Dictionary by Value in Python

 In order to create a program in Python which can sort a dictionary by value, the following prerequisites must be met. 

Now that you know the various prerequisites that will be required, let’s get down on how to actually write this program. 

 

Problem Statement 

 

Approach 

In order to create a program that addresses the above-shared problem statement, we will make use of the following functions as well as modules. 

Stay up-to-date with the latest Flutter features and best practices through our Flutter Course.

Practical Examples: Sort Dictionary by Value in Python

Now that all the functions and modules to be used have been explained, let’s look at a couple of examples to understand their implementation better. 

 

Example #1

def dictionairy():
key_value ={}

key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print ("First Taskn")
print ("Keys are")
for i in sorted (key_value.keys()) :
      print(i, end = " ")
def main():
      dictionairy()
if __name__=="__main__":
      main()

//Output:

First Task
Keys are
1 2 3 4 5 6

 

Example #2

def dictionairy():
key_value ={}
key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print ("Task 2:-nKeys and Values sorted in", "alphabetical order by the key ")
for i in sorted (key_value) :
      print ((i, key_value[i]), end =" ")
def main():
      dictionairy()
if __name__=="__main__":
      main()

//Output:

Task 2: -
Keys and Values sorted in alphabetical order by the key  
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)

 

Example #3

def dictionairy():
key_value ={}
key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print ("Task 3:-nKeys and Values sorted", "in alphabetical order by the value")
print(sorted(key_value.items(), key = lambda kv:(kv[1], kv[0])))
def main():
       dictionairy()
if __name__=="__main__":
       main()

//Output:

Task 3:-
Keys and Values sorted in alphabetical order by the value
[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]

 

Example #4

mydict = {"carl": 40, "alan": 2, "bob": 1, "danny": 3,}
for key in sorted(mydict.keys()):
       print("%s: %s" % (key, mydict[key]))

//Output:

alan: 2
bob: 1
carl: 40
danny: 3

 

Example #5

for key, value in sorted(mydict.items(), key=lambda item: item[1]):
    print("%s: %s" % (key, value))

 

The output for the above program will be,

bob: 1
alan: 2
danny: 3
carl: 40

 

Example #6

#!/usr/bin/env python
from __future__ import print_function
scores = {
   'Foo' : 10,
   'Bar' : 34,
   'Miu' : 88,
}
print(scores) # {'Miu': 88, 'Foo': 10, 'Bar': 34}
sorted_names = sorted(scores)
print(sorted_names)  # ['Bar', 'Foo', 'Miu']
for s in sorted_names:
    print("{}  {}".format(s, scores[s]))
print(sorted(scores.values())) # [10, 34, 88]
print('')
sorted_names = sorted(scores, key=lambda x: scores[x])
for k in sorted_names:
    print("{} : {}".format(k, scores[k]))
print('')
sorted_names = sorted(scores, key=scores.__getitem__)
for k in sorted_names:
    print("{} : {}".format(k, scores[k]))

 

With this, we come to an end of this article I hope you have understood how to sort a Dictionary in Python through some real-time examples.

Now that you have understood sorting basics through this “Sort Dictionary by Value in Python.” check out the Python online training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Python Programming Language training and certification courses are designed for students and professionals who want to be a Python Developer. The course is designed to give you a head start into Python programming and train you for both core and advanced Python concepts along with various Python frameworks like Django

Got a question for us? Mention it in the comments section of this blog and we will get back to you as soon as possible.

BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial