Computer Science
Predict the output:
arr = {}
arr[1] = 1
arr['1'] = 2
arr[1] += 1
sum = 0
for k in arr:
sum += arr[k]
print(sum)
Python Dictionaries
13 Likes
Answer
Output
4
Explanation
This python program computes the sum of values of items in the dictionary.
The arr dictionary is created and initialized with two key-value pairs, arr[1] = 1 and arr['1'] = 2. After that, the value of arr[1] is incremented by 1. At this point arr = {1: 2, '1': 2}.
The program iterates through each key k in the arr dictionary and adds the value arr[k] to the sum variable.
The final value of the sum variable is printed to the console.
Answered By
6 Likes
Related Questions
my_dict = {} my_dict[(1,2,4)] = 8 my_dict[[4,2,1]] = 10 print(my_dict)Predict the output:
fruit = {} L1 = ['Apple', 'banana', 'apple'] for index in L1 : if index in fruit: fruit[index] += 1 else : fruit[index] = 1 print(len(fruit)) print(fruit)Predict the output
a = {(1,2):1,(2,3):2} print(a[1,2])Predict the output
a = {'a':1, 'b':2, 'c':3} print(a['a','b'])