Reputation: 79
I'm working my way through the MIT 6.00 class on OpenCourseWare and don't quite understand a bit of code I've run into.
def deal_hand(n):
"""
Returns a random hand containing n lowercase letters.
At least n/3 the letters in the hand should be VOWELS.
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int >= 0
returns: dictionary (string -> int)
"""
hand={}
num_vowels = n / 3
for i in range(num_vowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(num_vowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
My question is about hand[x] = hand.get(x, 0) + 1
.
I understand that this looks up the value associated with a key (the key being either a vowel or consonant taken from a string initiated earlier in the script) and then adds 1 to it.
My question is how Python can look for the value associated with hand[x]
when it doesn't actually exist yet. When python gets to hand[x] = hand.get(x, 0) + 1
how does it assign a new value to a key that never existed to begin with (i.e. hand[x]
)?
Upvotes: 0
Views: 374
Reputation: 2123
The .get() method has an optional second parameter, specifying a default if it doesn't exist it. In this case it returns a 0 if the key x doesn't exist.
Upvotes: 3