CBSE Class 12 Computer Science Question 47 of 57

Review of Python Basics — Question 47

Back to all questions
47
Question

Question 42

Write a Python program to sort a dictionary by key.

Solution
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'}
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'}