Code Explanation:
Create a Dictionary Using a Dictionary Comprehension:
x = {i: i ** 2 for i in range(3)}
This creates a dictionary x where:
The keys are numbers generated by range(3) (i.e., 0, 1, and 2).
The values are the squares of the keys.
The resulting dictionary is:
x = {0: 0, 1: 1, 2: 4}
Access the Dictionary Keys:
y = x.keys()
x.keys() returns a dictionary view object that dynamically reflects the keys of the dictionary x.
At this point, y contains the keys of x: {0, 1, 2}.
Modify the Dictionary:
x[3] = 9
A new key-value pair is added to the dictionary x.
The dictionary now becomes:
x = {0: 0, 1: 1, 2: 4, 3: 9}
Convert the Keys to a List:
print(list(y))
Since y is a dictionary view object, it dynamically reflects the keys of the dictionary x.
Even though y was assigned before modifying x, it still reflects the updated dictionary x.
The keys of x at this point are [0, 1, 2, 3].
Final Output:
[0, 1, 2, 3]
0 Comments:
Post a Comment