In this example, we will learn how to sort a dictionary in python. In the below example we will sort a dictionary by key, value, and items.
Sort by key:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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
1 2 3 |
Sorted by key: ['1', '2', '3', '4'] |
Sory by value:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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
1 2 3 |
Sorted by value: ['Audi', 'BMW', 'Ford', 'Toyota'] |
Sort by Items:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
1 2 3 4 |
Sorted by key: [('1', 'Ford'), ('2', 'Toyota'), ('3', 'BMW'), ('4', 'Audi')] Sorted by value: [('4', 'Audi'), ('3', 'BMW'), ('1', 'Ford'), ('2', 'Toyota')] |