Question 34
What is the output of the following code?
Hint
With dictionaries, items() will create a collection of key-value pairs grouped together as tuples.
Iterate through them in the for loop and adjust the contents of data accordingly.
Solution
list(data.items()) produces [('a', 10), ('b', 12), ('c', 30)].
(key, value) |
value % 10 == 0? |
data |
|---|---|---|
('a', 10) |
10 % 10 == 0 (True) |
{'a': 5, 'b': 12, 'c': 30} |
('b', 12) |
12 % 10 == 0 (False) |
{'a': 5, 'b1': 24, 'c': 30} |
('c', 30) |
30 % 10 == 0 (True) |
{'a': 5, 'b1': 24, 'c': 15} |
By now, data = {'a': 5, 'b1': 24, 'c': 15}.
Print total, which is the sum of all the values inside data: 5 + 24 + 15 = 44.