Explanation:
Topics: for dictionary indexes add and assign operator
Try it yourself:
d = {}
print(d) # {}
d[1] = 1
print(d) # {1: 1}
d['1'] = 2
print(d) # {1: 1, '1': 2}
d[1] += 1
print(d) # {1: 2, '1': 2}
sum = 0
for k in d:
sum += d[k]
print("key: ", k, " - value: ", d[k])
# key: 1 - value: 2
print(sum) # 4
sum = 0
for k in d.keys():
sum += d[k]
print("key: ", k, " - value: ", d[k])
# key: 1 - value: 2
print(sum) # 4
The knowledge you need here is that a dictionary
can have indexes of different data types.
Therefore d[1] is a different index than d['1']
and they can both exist in the same dictionary.
To iterate through a dictionary is the same as
iterating through dict.keys()
In k will be the keys of the dictionary.
In this case 1 and '1'
The value of the first key will be 2
and the value of the other key will also be 2
and therefore (the) sum is 4