Default Dict Value in Python

Level 3103 keystrokes

This counts word occurrences using dict.get() with a default value. get() returns a default if the key doesn't exist.

Python code

# Start with an empty dictionary
1counts = {}
# Loop through each word in the list
2for word in ["a", "b", "a", "c", "a"]:
# get(key, default) returns the value or default if missing
# If word isn't in counts, return 0, then add 1
3 counts[word] = counts.get(word, 0) + 1
# Print the final count of each word
# Result: {'a': 3, 'b': 1, 'c': 1}
4print(counts)

Output

{'a': 3, 'b': 1, 'c': 1}
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 10
  • ,× 5
  • (× 2
  • )× 2
  • [× 2
  • ]× 2
  • =× 2
  • :× 1
  • .× 1
  • {× 1

More Python examples at level 3

← Python typing practice