Dict Setdefault in Python

Level 3109 keystrokes

This uses setdefault() to initialize dictionary values before incrementing, avoiding KeyError.

Python code

# Create an empty dictionary for counting
1counts = {}
# Iterate over list of words
2for word in ["a", "b", "a", "c", "a"]:
# setdefault sets value to 0 if key doesn't exist
# If key exists, returns current value without changing it
3 counts.setdefault(word, 0)
# Increment the count for this word
4 counts[word] += 1
# Print final counts: {'a': 3, 'b': 1, 'c': 1}
5print(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