Step 1 — Dictionary Creation
d = {'a':1, 'b':2, 'c':3}Creates a dictionary with:
๐น Step 2 — Getting Keys
d.keys()Returns a view object of dictionary keys:
dict_keys(['a', 'b', 'c'])๐น Step 3 — Converting to List
list(d.keys())Turns that into a list:
['a', 'b', 'c']๐น Step 4 — Reversing the List
reversed(list(d.keys()))Creates a reversed iterator:
['c', 'b', 'a']๐น Step 5 — Looping
The loop prints each key (k) from the reversed list, separated by a space.
Output:
c b aKey Takeaway:
reversed() works only on sequences like lists or tuples, not directly on dict_keys.
-
That’s why we use list(d.keys()).
-
Dictionaries in Python preserve insertion order, so reversing the key list prints keys in the opposite order of insertion.


0 Comments:
Post a Comment