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 counting1counts = {}# Iterate over list of words2for 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 it3 counts.setdefault(word, 0) # Increment the count for this word4 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. 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