Hey! Hope everyone’s learning is going well.
The following is what I thought was a neat snippet a friend showed me in JavaScript that can be translated to Python for incrementing a dictionary’s value at a key regardless of whether it exists already. Just started on the site so I’m not sure if this covered anywhere. Uses include structures like frequency counters.
frequencies = {}
for word in doc:
`frequencies[word] = (frequencies.get(word) or 0) + 1`
How it works
- If
frequencies.get(word)
returns a value then that is added to1
- If it does not, then
0
is returned from the expression in the parentheses and added to1
Please do not do the following
`frequencies[word] = (frequencies[word] or 0) + 1`
Attempting to index a dictionary at a key that does not exist throws an error!