Skip to content

Question 34

What is the output of the following code?

data = {'a': 10, 'b': 12, 'c': 30}
for key, value in list(data.items()):
    if value % 10 == 0:
        data[key] = value // 2
    else:
        data[key + '1'] = value * 2
        del data[key]

total = sum(data.values())
print(total)
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.

Answer
44