Python Clean Code:
The
Instead of writing
Example👇
#Python #CleanCode #PythonTips #DataStructures #CodeReadability
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
The
collections.defaultdict simplifies dictionary creation by providing a default value for keys that have not been set yet, eliminating the need for manual existence checks.Instead of writing
if key not in my_dict: before initializing a value (like a list or a counter), defaultdict handles this logic automatically upon the first access of a missing key. This prevents KeyError and makes grouping and counting code significantly cleaner.Example👇
>>> from collections import defaultdict
>>>
>>> # Cluttered way with a standard dict
>>> data = [('fruit', 'apple'), ('veg', 'carrot'), ('fruit', 'banana')]
>>> grouped_data = {}
>>> for category, item in data:
... if category not in grouped_data:
... grouped_data[category] = []
... grouped_data[category].append(item)
...
>>> # Clean way with defaultdict
>>> clean_grouped_data = defaultdict(list)
>>> for category, item in data:
... clean_grouped_data[category].append(item)
...
>>> clean_grouped_data
defaultdict(<class 'list'>, {'fruit': ['apple', 'banana'], 'veg': ['carrot']})
#Python #CleanCode #PythonTips #DataStructures #CodeReadability
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨