Just a quick one: neat way to increment dictionary key if it does not exist in one line

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 to 1
  • If it does not, then 0 is returned from the expression in the parentheses and added to 1

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!

1 Like

@jr22,

One could also type it as:

for word in frequencies:
    frequencies[word] = frequencies.get(word,0) + 1

The general form is .get(dictionary key, value to return if key the is not found).
.get() returns a default value of None if dictionary key is not found.