I'm trying to understand following python code as I'm new to it.
import random
howMany = random.randint(0,1000)
stats = {}
for i in range(howMany):
value = random.randint(0,500)
stats.setdefault(value,0)
stats[value]+=1
for item in stats:
if stats[item] > 1:
print item
Here is what I have understood so far, my questions will follow afterwards:
howMany
stores the random number generated between 0 & 1000 inclusive of both.stats = {}
declares an empty dictionaryi
will run depending upon the value ofhowMany
. For example ifhowMany
was 2 soi
will run for two times with values is0
and1
.value
variable stores random number between0
&500
inclusive of bothI didn't understand
stats.setdefault(value,0)
. For example, thevalue
variable has value4
, thenstats.setdefault(4,0)
means what?What does
stats[value]+=1
do? The expanded form ofstats[value]+=1
isstats[value] = value + 1
?I understood the following paragraph:
for item in stats: if stats[item] > 1: print item
Those values are printed which are greater than
1
in thestats
dictionary. Please correct me if I'm wrong somewhere.