How to use sorted() method In Python

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.

Syntax:

To sort based on items:
for i in sorted(dictionary.items()) :
     print(i, end = " ")

To sort based on keys:
for i in sorted(dictionary.keys()) :
     print(i, end = " ") 
     
To sort based on values:
for i in sorted(dictionary.values()) :
     print(i, end = " ")           

Example 1:

Python3




# declare a dictionary of tuple with student data
data = {'student1': ('bhanu', 10), 'student4': ('uma', 12),
        'student3': ('suma', 11), 'student2': ('ravi', 11),
        'student5': ('gayatri', 9)}
 
# sort student dictionary based  on items
for i in sorted(data.items()):
    print(i, end=" ")
print()
 
# sort student dictionary based  on values
for i in sorted(data.values()):
    print(i, end=" ")
print()
 
# sort student dictionary based  on keys
for i in sorted(data.keys()):
    print(i, end=" ")


Output:

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

(‘bhanu’, 10) (‘gayatri’, 9) (‘ravi’, 11) (‘suma’, 11) (‘uma’, 12) 

student1 student2 student3 student4 student5

We can make a dictionary of tuple with key as tuple also.

Example 2:

Python program to create a dictionary of tuple with a tuple as key and apply sorted() function

Python3




# 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 based  on items
for i in sorted(data.items()):
    print(i, end=" ")
print()
 
# sort student dictionary based  on values
for i in sorted(data.values()):
    print(i, end=" ")
print()
 
# sort student dictionary based  on keys
for i in sorted(data.keys()):
    print(i, end=" ")


Output:

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

student1 student2 student3 student4 student5 

(‘bhanu’, 10) (‘gayatri’, 9) (‘ravi’, 11) (‘suma’, 11) (‘uma’, 12)

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

...