CBSE Class 12 Computer Science Question 93 of 105

Python Revision Tour II — Question 20

Back to all questions
20
Question

Question 13

What will be the output of the following code snippet ?

my_dict = {}  
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
    sum += my_dict[k]
print(sum)
print(my_dict)
Answer
Output
30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
Explanation
  1. An empty dictionary named my_dict is initialized.
  2. my_dict[(1,2,4)] = 8, my_dict[(4,2,1)] = 10, my_dict[(1,2)] = 12 these lines assign values to the dictionary my_dict with keys as tuples. Since tuples are immutable, so they can be used as keys in the dictionary.
  3. The for loop iterates over the keys of the dictionary my_dict. Inside the loop, the value associated with each key k is added to the variable sum.
  4. sum and my_dict are printed.