Django Training and Certification (7 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

Understand How to Sort Dictionary by Value in Python

Last updated on Jun 19,2023 17K Views


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.

 

python - edurekaPrerequisites: 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. 

  • Dictionary: In Python dictionary can be defined as an unorganized collection of data that is used to store data values like maps, and other elements that hold a key-value pair. 
  • List: A list is similar to arrays in Python; it might contain a collection of various data items such as strings, integers, floating numbers etc. 
  • Merging Two Dictionaries: Merging two dictionaries is an internal function in Python that can be achieved quite easily. 
  • Dictionary Methods: Dictionary methods is again a Python internal function that will be used in the context of this program.

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

 

Problem Statement 

sort-dictionary-by-value-in-python-edureka-problem statement

  • Create a dictionary and arrange as well as display all its keys alphabetically. 
  • Display the key-values as well as names alphabetically and display them. 

 

Approach 

sort-dictionary-by-value-in-python-edureka-problem solution

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. 

  • Make use of the key_value.iterkeys()  function to sort all the keys alphabetically. 
  • Use the sorted (key_value) to sort all the values alphabetically and print them onto the screen of the user. 
  • Sort the final list of key values using the functions key_value.iteritems(), key = lambda (k, v) : (v, k)).

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

Practical Examples: Sort Dictionary by Value in Python

sort-dictionary-by-value-in-python-edureka-problem example

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.

Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Understand How to Sort Dictionary by Value in Python

edureka.co