Skip to content
Related Articles

Related Articles

Improve Article
Python | Get items in sorted order from given dictionary
  • Last Updated : 28 Feb, 2019

Given a dictionary, the task is to get all items from the dictionary in sorted order. Let’s discuss different ways we can do this task.

Method #1: Using sorted()




# Python code to demonstrate
# to get sorted items from dictionary
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print ("iniial_dictionary", str(ini_dict))
  
# getting items in sorted order
print ("\nItems in sorted order")
for key in sorted(ini_dict):
    print (ini_dict[key])
Output:
iniial_dictionary {'b': 'bhuvan', 'c': 'chandan', 'a': 'akshat'}

Items in sorted order
akshat
bhuvan
chandan

 
Method #2: Using d.items()




# Python code to demonstrate
# to get sorted items from dictionary
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print ("iniial_dictionary", str(ini_dict))
  
# getting items in sorted order
print ("\nItems in sorted order")
for key, value in sorted(ini_dict.items()):
    print(value)
Output:



iniial_dictionary {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'}

Items in sorted order
akshat
bhuvan
chandan

 

Method #3: Using operator




# Python code to demonstrate
# to get sorted items from dictionary
  
import operator
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print "iniial_dictionary", str(ini_dict)
  
# getting items in sorted order
print ("\nItems in sorted order")
for key, value in sorted(ini_dict.iteritems(),
                         key = operator.itemgetter(1), 
                         reverse = False):
    print key, " ", value
Output:
iniial_dictionary {'a': 'akshat', 'c': 'chandan', 'b': 'bhuvan'}

Items in sorted order
a   akshat
b   bhuvan
c   chandan

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :