sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print("Original list ", sample_list)
count_dict = dict()
for item in sample_list:
if item in count_dict:
count_dict[item] += 1 # how was the data stored into the variable count_dict?
else:
count_dict[item] = 1
print("Printing count of each item ", count_dict)
i just don’t understand how the program works
>Solution :
If number not in dict then program create key (number) with value 1. If same number appears in loop again and dict already have this key then value of this key increases by 1.
In result there would be count_dict where keys are numbers from sample_list and values are count of key in sample_list.
If sample_list = [1, 1, 1]
Then count_dict = {1: 3}
For example 11 appears in sample_list 2 times then count_dict[11] would be equal to 2.