Chris Clark Chris Clark - 6 months ago 8
Python Question

Python is... Well, it's doing two things at once with the same syntax AND operator?

I really don't know what to call this, the closest thing I can think in c# terms is "syntax candy".

I am learning some python for data science reasons. The book I am reading on is covering some basics of

Python
. Here is an example they are demonstrating.


... An obvious approach is to create a dictionary in which the keys are words and values are counts. As you check each word, you can increment its count if it's already in the dictionary and add it to the dictionary if it's not:


word_counts = {}
for word in document:
if word in word_counts:
word_counts[word] +=1
else:
word_counts[word] = 1


Why does
word_counts[word]
create a key if the key does not exist and then assign the value to
1
?

If I was to do:

word_counts[word]


does that create a key with no value?

I feel like this could start some problems in OOD.

EDIT

If
word_counts[word]
is creating the key, then
= 1
is assigning the value.

Why not just have your language do the same thing with
word_counts[word] += 1
?

Answer

This seems to be the core of your misunderstanding:

but word_counts[word] is creating the key, then =1 is assigning the value

No. Unlike in, say, C++, item assignment is a single operation, not the combination of item retrieval and the assignment operator. There are no separate "create entry" and "assign value" steps. The syntax is (mostly) equivalent to

word_counts.__setitem__(word, 1)

If you take exception to the fact that creating the entry and setting its value are a single step, well, you can't reasonably separate them. If you try to make "create the entry" and "set its value" separate steps, then the entry is in an incompletely initialized state in between those steps. We'd have to define what happens when you try to access a dict entry with no value, and it'd overall be confusing and useless.

If word_counts[word] is null it creates the key, and assignes the value to 1?

No. If word_counts does not have an entry for the key word, then this:

if word in word_counts:

selects the else branch, and this:

else:
    word_counts[word] = 1

creates an entry in word_counts with key word and value 1.

What if I do this...

word_counts[word]

If there's no existing entry with key word, that produces a KeyError.