Code Explanation:
Line 1: Import MappingProxyType
from types import MappingProxyType
Explanation
Imports the MappingProxyType class from Python's built-in types module.
MappingProxyType creates a read-only (immutable) view of a dictionary.
The view itself cannot be modified, but it always reflects changes made to the original dictionary.
Line 2: Create a Dictionary
d = {"a": 10}
Explanation
A dictionary named d is created.
Current dictionary:
{
"a": 10
}
Number of items = 1
Line 3: Create a Read-Only View
view = MappingProxyType(d)
Explanation
Creates a read-only view of d.
view points to the same dictionary.
No copy of the dictionary is created.
Current state:
d
↓
{"a":10}
view
↓
Read-only view of d
Line 4: Modify the Original Dictionary
d["b"] = 20
Explanation
A new key-value pair is added to the original dictionary.
Dictionary becomes:
{
"a": 10,
"b": 20
}
Since view is linked to the original dictionary, it automatically reflects this update.
Now view contains:
{
"a":10,
"b":20
}
Line 5: Print the Length
print(len(view))
Explanation
len(view) counts the number of key-value pairs visible through the read-only view.
Current view:
{
"a":10,
"b":20
}
Total items = 2
Output
2

0 Comments:
Post a Comment