CBSE Class 12 Computer Science
Question 22 of 22
Python Revision Tour II — Question 12
Back to all questions 12
Question Write a program to sort a dictionary's values using Bubble sort and produce the sorted values as a list.
my_dict = eval(input("Enter the dictionary: "))
values = list(my_dict.values())
l = len(values)
for i in range(l):
for j in range(0, l - i - 1):
if values[j] > values[j + 1]:
# Swap values
values[j], values[j + 1] = values[j + 1], values[j]
print("Sorted values:", values)Enter the dictionary: {'w':34, 'a':5, 'g':45, 't':21}
Sorted values: [5, 21, 34, 45]
my_dict
=
eval
(
input
(
"Enter the dictionary: "
))
values
=
list
(
my_dict
.
values
())
l
=
len
(
values
)
for
i
in
range
(
l
):
for
j
in
range
(
0
,
l
-
i
-
1
):
if
values
[
j
]
>
values
[
j
+
1
]:
# Swap values
values
[
j
],
values
[
j
+
1
]
=
values
[
j
+
1
],
values
[
j
]
print
(
"Sorted values:"
,
values
)
Output
Enter the dictionary: {'w':34, 'a':5, 'g':45, 't':21}
Sorted values: [5, 21, 34, 45]