Question 15
Predict the output :
dct = {}
dct[1] = 1
dct ['1'] = 2
dct[1.0] = 4
sum = 0
for k in dct:
print(k, sum)
sum += dct[k]
print(sum)Output
1 0
1 4
6
Explanation
This python program computes the sum of values of items in the dictionary. It also demonstrates that dictionaries in Python can have both integer and string keys, but the keys must be unique.
The keys 1 and '1' will be treated as two different keys as the former is a number and the latter is a string. But the keys 1 and 1.0 are considered the same as both represent number 1.
Here is a step-by-step explanation of the program:
1. The dct dictionary is created and initialized with two key-value pairs, dct[1] = 1 and dct['1'] = 2.
2. After that, dct[1.0] = 4 updates the value of key 1 to 4 as the keys 1 and 1.0 are considered the same. At this point, dct = {1: 4, '1': 2}.
3. Loop through each key k in dct. Below table shows the loop iterations:
| k | dct[k] | sum | Iteration |
|---|---|---|---|
| 1 | 4 | 0 + 4 = 4 | Iteration 1 |
| '1' | 2 | 4 + 2 = 6 | Iteration 2 |
4. The final value of the sum variable is printed to the console.