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
3 Likes
Related Questions
Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys.
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Write a Python script to merge two Python dictionaries.
Write a Python program to combine two dictionaries adding values for common keys.
d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400}
Sample output:
Counter({'a': 400, 'b': 400, 'c': 300, 'd': 400})
Write a Python program to find the three highest values in a dictionary.