🔹 Step 1: d = {}
An empty dictionary is created.
So right now:
d = {}
There are no keys inside it.
🔹 Step 2: print(d.get("x"))
-
.get("x")tries to retrieve the value of key"x". -
Since
"x"does not exist, it does NOT raise an error. -
Instead, it returns None (default value).
So this line prints:
None
👉 .get() is a safe way to access dictionary values.
You can even set a default:
d.get("x", 0)
This would return 0 instead of None.
🔹 Step 3: print(d["x"])
-
This tries to access key
"x"directly. -
Since
"x"is not present, Python raises:
KeyError: 'x'
So the program stops here with an error.
Final Output
None
KeyError: 'x'
(Program crashes after the error.)
Key Difference
| Method | If Key Exists | If Key Missing |
|---|---|---|
d.get("x") | Returns value | Returns None |
d["x"] | Returns value | ❌ Raises KeyError |
Why This Is Important?
In real projects (especially APIs & data processing):
-
Use
.get()when you are not sure the key exists. -
Use
[]when the key must exist (and error is acceptable).


0 Comments:
Post a Comment