CBSE Class 12 Computer Science Question 21 of 22

Python Revision Tour II — Question 11

Back to all questions
11
Question

Question 11

Write a program to sort a dictionary's keys using Bubble sort and produce the sorted keys as a list.

Solution
my_dict = eval(input("Enter the dictionary: "))
keys = list(my_dict.keys())
l = len(keys)
for i in range(l):
    for j in range(0, l - i - 1):
        if keys[j] > keys[j + 1]:
            keys[j], keys[j + 1] = keys[j + 1], keys[j]
print("Sorted keys:",keys)
Output
Enter the dictionary: {'c':10, 'f':87, 'r':23, 'a':5}
Sorted keys: ['a', 'c', 'f', 'r']
Answer

my_dict
=
eval
(
input
(
"Enter the dictionary: "
))
keys
=
list
(
my_dict
.
keys
())
l
=
len
(
keys
)
for
i
in
range
(
l
):
for
j
in
range
(
0
,
l
-
i
-
1
):
if
keys
[
j
]
>
keys
[
j
+
1
]:
keys
[
j
],
keys
[
j
+
1
]
=
keys
[
j
+
1
],
keys
[
j
]
print
(
"Sorted keys:"
,
keys
)
Output
Enter the dictionary: {'c':10, 'f':87, 'r':23, 'a':5}
Sorted keys: ['a', 'c', 'f', 'r']