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')]
Comments (0)