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)
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:
| 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.
Related Questions
Predict the output
a = {'a':1, 'b':2, 'c':3} print(a['a','b'])Find the error/output. Consider below given two sets of codes. Which one will produce an error? Also, predict the output produced by the correct code.
(a)
box = {} jars = {'Jam' :4} crates = {} box['biscuit'] = 1 box['cake'] = 3 crates['box'] = box crates['jars'] = jars print(len(crates[box]))(b)
box = {} jars = {'Jam' :4} crates = {} box['biscuit'] = 1 box['cake'] = 3 crates['box'] = box crates['jars'] = jars print(len(crates['box']))Fill in the blanks of the following code so that the values and keys of dictionary d are inverted to create dictionary fd.
d = {'a':1, 'b':2, 'c':3} print(d) fd = {} for key, value in d.____(): fd[____] = ____ print(fd)Write a program to enter names of employees and their salaries as input and store them in a dictionary.