Python | Get items in sorted order from given dictionary

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()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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])

chevron_right


Output:



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

Items in sorted order
akshat
bhuvan
chandan

 
Method #2: Using d.items()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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

Items in sorted order
akshat
bhuvan
chandan

 

Method #3: Using operator

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.