Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I deleted my dict, but my dict_keys don't mind, why is that?

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?

like image 772
Dimitris Fasarakis Hilliard Avatar asked Feb 10 '17 14:02

Dimitris Fasarakis Hilliard


People also ask

What can a dictionary hold?

Just like lists, the values of dictionaries can hold heterogeneous data i.e., integers, floats, strings, NaN, Booleans, lists, arrays, and even nested dictionaries.

How many identical keys can a dictionary have?

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.

Is dictionary a sequence?

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.


1 Answers

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)
[]
like image 180
zwol Avatar answered Sep 25 '22 08:09

zwol