CBSE Class 11 Computer Science Question 43 of 112

Dictionaries — Question 23

Back to all questions
23
Question

Question 23

What will be the output of following Python code?

d1 = {"a":10,"b":2,"c":3}
str1=""
for i in d1:
    str1 = str1 + str(d1[i]) + " " 
    str2 = str1[:-1]
print(str2[::-1])
  1. 3, 2
  2. 3, 2, 10
  3. 3, 2, 01
  4. Error
Answer

3, 2, 01

Reason — d1 is a dictionary containing three elements. str1 is initialized to an empty string.
Inside the for loop, the values of dictionary d1 are getting concatenated to str1 as a string. The statement str2 = str1[:-1] takes a slice of str1 from start to end and assigns to str2. So effectively, this statement is assigning str1 to str2.
The detailed execution of the for loop is shown in the table below:

id1[i]str(d1[i])str1str2
"a"10"10""10 ""10"
"b"2"2""10 2 ""10 2"
"c"3"3""10 2 3 ""10 2 3"

Now the expression str2[::-1] will reverse the string "10 2 3" to '3 2 01'