Computer Science

Write a Python program to sort a dictionary by key.

Python

Python Sorting

1 Like

Answer

def bubble_sort_keys(keys):
    n = len(keys)
    for i in range(n - 1):
        for j in range(0, n - i - 1):
            if keys[j] > keys[j + 1]:
                keys[j], keys[j + 1] = keys[j + 1], keys[j]

my_dict = eval(input("Enter the dictionary: "))
keys_list = list(my_dict.keys())
bubble_sort_keys(keys_list)
sorted_dict = {}
for key in keys_list:
    sorted_dict[key] = my_dict[key]

print("Dictionary sorted by key:", sorted_dict)

Output

Enter the dictionary: {51 : "Orange", 21: "Mango", 13 : "Watermelon"}
Dictionary sorted by key: {13: 'Watermelon', 21: 'Mango', 51: 'Orange'}

Answered By

2 Likes


Related Questions