DefaultDict Usage in Python
Level 4179 keystrokes
This uses defaultdict to automatically create default values. Missing keys get initialized with the factory function (list).
Python code
# Import defaultdict from collections module1from collections import defaultdict2 # Create defaultdict with list as default factory3groups = defaultdict(list)# Sample data as list of tuples (key, value)4data = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]5 # Iterate through key-value pairs6for key, val in data: # Automatically creates empty list if key doesn't exist7 groups[key].append(val)8 # Convert to regular dict and print9print(dict(groups))Output
{'a': [1, 3], 'b': [2, 4]}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.
,× 8"× 8(× 8)× 8[× 2]× 2=× 2:× 1.× 1