Computer Science
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])
- 3, 2
- 3, 2, 10
- 3, 2, 01
- Error
Python Dictionaries
7 Likes
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:
| i | d1[i] | str(d1[i]) | str1 | str2 |
|---|---|---|---|---|
| "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'
Answered By
2 Likes
Related Questions
Which of the following will give error if d1 is as shown below?
d1 = {"a":1, "b":2, "c":3}- print(len(d1))
- print(d1.get("b"))
- d1["a"] = 5
- None of these
Which of the following Python codes will give the same output if
dict = {"diary":1, "book":3, "novel":5}(i) dict.pop("book")
(ii) del dict["book"]
(iii) dict.update({"diary":1,"novel":5})- (i), (ii), (iii)
- (1), (ii)
- (i), (iii)
- (ii), (iii)
Running the code sorted(mydictionary, reverse = True) on a dictionary named mydictionary will return results sorted in what order?
- Ascending order (A-Z), by key
- Ascending order (A-Z), by value
- Descending order (Z-A), by key
- Descending order (Z-A), by value
Fill in the blanks:
The keys of a dictionary must be of _________ types.