The keys()
and values()
methods don’t return lists. As the exercise mentions, if we just want to iterate over the keys or values of a dictionary, then the objects returned by these methods are sufficient and we don’t need to convert them to lists. But, that doesn’t mean that they actually are lists. If you want to use list methods (such as sort/append/pop) on the objects returned by the keys()
and values()
methods, then we need to convert the objects into lists.
d = {"a": 44, "d": 455, "z": 18, "b": 0, "n": 19, "f": 100}
x = d.keys() # dict_keys object
y = d.values() # dict_values object
# Can iterate over the objects without having to convert them into lists
for value in y:
print(value)
# And also do some other things without having to convert to lists
for value in reversed(y):
print(value)
print(len(y)) # 6
print(19 in y) # True
# But we can't append/sort/pop these objects
y.append(11) # AttributeError
y.pop() # AttributeError
y.sort() # AttributeError
print(y)
# dict_values([44, 455, 18, 0, 19, 100])
y = list(y) # [44, 455, 18, 0, 19, 100]
y.append(11) # [44, 455, 18, 0, 19, 100, 11]
y.pop() # [44, 455, 18, 0, 19, 100]
y.sort() # [0, 18, 19, 44, 100, 455]
Furthermore, the objects returned by the keys()
and values()
methods
provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. (documentation)
d = {"a": 44, "d": 455, "z": 18, "b": 0, "n": 19, "f": 100}
x = d.keys()
print(x)
# dict_keys(['a', 'd', 'z', 'b', 'n', 'f'])
del d["z"]
d["x"] = 999
print(x)
# dict_keys(['a', 'd', 'b', 'n', 'f', 'x'])
# Even though, we didn't invoke the .keys() method again,
# the object is dynamic and reflects changes made to dictionary.