Skip to content
Related Articles

Related Articles

Python | Get items in sorted order from given dictionary

View Discussion
Improve Article
Save Article
Like Article
  • 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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!