KnowledgeBoat Logo
|

Computer Science

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)

Python Dictionaries

25 Likes

Answer

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:

kdct[k]sumIteration
140 + 4 = 4Iteration 1
'1'24 + 2 = 6Iteration 2

4. The final value of the sum variable is printed to the console.

Answered By

10 Likes


Related Questions