DefaultDict in Python
Level 4252 keystrokes
This uses defaultdict to automatically create default values for missing keys, useful for grouping data.
Python code
# Import defaultdict from collections1from collections import defaultdict2 # Missing keys automatically get an empty list3groups = defaultdict(list)# (category, item) pairs to group4data = [("fruit", "apple"), ("veg", "carrot"), ("fruit", "banana")]5 # Unpack each pair into category and item6for category, item in data: # No need to check if the key exists before append7 groups[category].append(item)8 # Loop over each key and its list (in insertion order)9for key, values in groups.items(): # Prints fruit: ['apple', 'banana'] and veg: ['carrot']10 print(f"{key}: {values}")Output
fruit: ['apple', 'banana'] veg: ['carrot']
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.
"× 14,× 7(× 7)× 7:× 3.× 2[× 2]× 2{× 2}× 2