Since dict.keys
(and dict.items
and dict.values
alike) returns a view of the dictionary object, I would assume that deleting the dictionary they were produced from to actually have an effect on the dict_keys
we got them from.
With a simple dictionary and it's keys:
d = {i:i for i in range(20)}
k = d.keys() # similarly with d.values and d.items
Apparently, this isn't the case:
del d
i = iter(k)
list(i) # works fine and prints the keys
Does anyone know why this is the case?
Just like lists, the values of dictionaries can hold heterogeneous data i.e., integers, floats, strings, NaN, Booleans, lists, arrays, and even nested dictionaries.
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored.
The dictionary is the first compound type that we've seen that is not a sequence, so we can't index or slice a dictionary.
del d
deletes the variable d
, but the object that it refers to will continue to exist if there are other references. You don't need a dictionary view to observe this:
>>> d = {i:i for i in range(5)}
>>> dd = d
>>> d['x'] = 'x'
>>> del d
>>> d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
>>> dd
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 'x': 'x'}
(The d['x']='x'
line demonstrates that dd=d
does not copy the dictionary itself, it only makes an additional reference.)
Also contrast the behavior of clear
, which modifies the actual object:
>>> d = {i:i for i in range(5)}
>>> k = d.keys()
>>> del d
>>> list(k)
[0, 1, 2, 3, 4]
>>> d = {i:i for i in range(5)}
>>> k = d.keys()
>>> d.clear()
>>> list(k)
[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With