Let’s break it down step by step:
Code
Explanation
-
defaultdict(list)
-
This creates a dictionary where every new key automatically starts with a default empty list ([]).
-
If you access a missing key, it doesn’t raise KeyError (like normal dict). Instead, it creates a new entry with [] as the value.
-
-
d['a'].append(10)
-
Key 'a' doesn’t exist initially, so defaultdict creates it with a new list [].
-
Then 10 is appended.
-
Now d = {'a': [10]}.
-
-
print(d['b'])
-
Key 'b' doesn’t exist, so defaultdict creates it automatically with a default list() (which is []).
-
Nothing is appended, so it just prints
[].
-
✅ Final Output
[]
⚡Key point: defaultdict(list) avoids KeyError by supplying a default empty list for missing keys.


0 Comments:
Post a Comment