Let’s break it down step by step ๐
Code:
Explanation:
-
defaultdict(int)
-
Creates a dictionary-like object.
-
When you try to access a key that doesn’t exist, it automatically creates it with a default value.
-
Here, the default value is given by int(), which returns 0.
-
-
d['a'] += 1
-
Since 'a' is not yet in the dictionary, defaultdict creates it with 0 as the default.
-
Then, 0 + 1 = 1.
-
Now, d = {'a': 1}.
-
-
print(d['b'])
'b' doesn’t exist in the dictionary.
defaultdict automatically creates it with default value int() → 0.
-
So, it prints 0.
-
Now, d = {'a': 1, 'b': 0}.
Final Output:
0
⚡ Key Point: Unlike a normal dict, accessing a missing key in defaultdict does not raise a KeyError. Instead, it inserts the key with a default value.


0 Comments:
Post a Comment