Sorting a Dictionary by Keys or Values
In Python, dictionaries can be sorted by either keys or values. Below are examples demonstrating how to sort a dictionary using different methods.
Example 1: Sorting by Keys
def dictionairy(): # Declare dictionary key_value = {} # Initialize values key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("Sorting by keys:") # Sorted by keys for i in sorted(key_value): print((i, key_value[i]), end=" ") def main(): dictionairy() if __name__ == "__main__": main()
Output:
Sorting by keys: (1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
Example 2: Sorting by Values
def dictionairy(): # Declare dictionary key_value = {} # Initialize values key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("Sorting by values:") print(sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))) def main(): dictionairy() if __name__ == "__main__": main()
Output:
Sorting by values: [(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]
Example 3: Sorting a List of Dictionaries
lis = [ {"name": "Taobao", "age": 100}, {"name": "Runoob", "age": 7}, {"name": "Google", "age": 100}, {"name": "Wiki", "age": 200} ] # Sorting by age (ascending) print("Sorting by age (ascending):") print(sorted(lis, key=lambda i: i['age'])) print("\r") # Sorting by age and then by name print("Sorting by age and name:") print(sorted(lis, key=lambda i: (i['age'], i['name']))) print("\r") # Sorting by age (descending) print("Sorting by age (descending):") print(sorted(lis, key=lambda i: i['age'], reverse=True))
Output:
Sorting by age (ascending): [{'name': 'Runoob', 'age': 7}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Wiki', 'age': 200}] Sorting by age and name: [{'name': 'Runoob', 'age': 7}, {'name': 'Google', 'age': 100}, {'name': 'Taobao', 'age': 100}, {'name': 'Wiki', 'age': 200}] Sorting by age (descending): [{'name': 'Wiki', 'age': 200}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Runoob', 'age': 7}]