TutorialClues TutorialClues
Updated date Mar 23, 2021
In this code snippet, we will see how to sort a dictionary in python. In the below example we will sort a dictionary by key, value, and items.

In this code snippet, we will see how to sort a dictionary in python. In the below code example we will sort a dictionary by key, value, and items.

Sort by key:

dict = {}
dict['1'] = 'Ford'
dict['4'] = 'Audi'
dict['2'] = 'Toyota'
dict['3'] = 'BMW'

# Get list of keys
list = dict.keys()

# Sorted by key
print("Sorted by key: ", sorted(list))

Output:

Sorted by key:  ['1', '2', '3', '4']

Sory by value:

dict = {}
dict['1'] = 'Ford'
dict['4'] = 'Audi'
dict['2'] = 'Toyota'
dict['3'] = 'BMW'

# Get list of values
list = dict.values()

# Sorted by key
print("Sorted by value: ", sorted(list))

Output:

Sorted by value:  ['Audi', 'BMW', 'Ford', 'Toyota']

Sort by Items:

dict = {}
dict['1'] = 'Ford'
dict['4'] = 'Audi'
dict['2'] = 'Toyota'
dict['3'] = 'BMW'

// Get items
list = dict.items()

# Sorted by key
print("Sorted by key: ", sorted(list, key = lambda y : y[0]))

#Sorted by value
print("Sorted by value: ", sorted(list, key = lambda y : y[1]))

Output:

Sorted by key:  [('1', 'Ford'), ('2', 'Toyota'), ('3', 'BMW'), ('4', 'Audi')]
Sorted by value:  [('4', 'Audi'), ('3', 'BMW'), ('1', 'Ford'), ('2', 'Toyota')]

 

ABOUT THE AUTHOR

TutorialClues
TutorialClues
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.tutorialclues.com/profile/tutorialclues

Comments (0)

There are no comments. Be the first to comment!!!