How to use OrderedDict In Python

OrderedDict is available in the collections module used to sort a dictionary with sorted() method.

Syntax:

To sort based on values:
OrderedDict(sorted(dictionary.values())

To sort based on items:
OrderedDict(sorted(dictionary.items())

Example 1: Python program to sort dictionary of tuple

Python3




# import OrderedDict module
from collections import OrderedDict
 
# declare a dictionary of tuple with student data
data = {'student3': ('bhanu', 10), 'student2': ('uma', 12),
        'student4': ('sai', 11), 'student1': ('suma', 11)}
 
# sort student dictionary of tuple based
# on values using OrderedDict
print(OrderedDict(sorted(data.values())))
print()
 
# sort student dictionary of tuple based
# on items using OrderedDict
print(OrderedDict(sorted(data.items())))


Output:

OrderedDict([(‘bhanu’, 10), (‘sai’, 11), (‘suma’, 11), (‘uma’, 12)])

OrderedDict([(‘student1’, (‘suma’, 11)), (‘student2’, (‘uma’, 12)), (‘student3’, (‘bhanu’, 10)), (‘student4’, (‘sai’, 11))])

Example 2: Python program to  sort the dictionary of tuples where the Tuples will be the key in the dictionary

Python3




# import orderedDict module
from collections import OrderedDict
 
# declare a dictionary of tuple with student data
data = {('bhanu', 10): 'student1',
        ('uma', 12): 'student4',
        ('suma', 11): 'student3',
        ('ravi', 11): 'student2',
        ('gayatri', 9): 'student5'}
 
# sort student dictionary of tuple based
# on items using OrderedDict
print(OrderedDict(sorted(data.items())))


Output:

OrderedDict([((‘bhanu’, 10), ‘student1’), ((‘gayatri’, 9), ‘student5’), ((‘ravi’, 11), ‘student2’), ((‘suma’, 11), ‘student3’), ((‘uma’, 12), ‘student4’)])



Python – Sorting a dictionary of tuples

In this article, we will sort a dictionary of tuples. Dictionary of tuples means tuple is a value in a dictionary or tuple is key in the dictionary.

Example:

{'key1': (1, 2, 3), 'key2': (3, 2, 1),.............}
or
{ (1, 2, 3):value, (3, 2, 1):value,.............}

Similar Reads

Method 1: Using sorted() method

Using this method we can sort the dictionary of tuples based on keys, values, and items, we can use for loop to sort all elements in a dictionary of tuples....

Method 2: Using OrderedDict

...