Python 3: dict & dict.keys()

Ethan Furman ethan at stoneleaf.us
Tue Jul 23 21:16:08 EDT 2013


Back in Python 2.x days I had a good grip on dict and dict.keys(), and when to use one or the other.

Then Python 3 came on the scene with these things called 'views', and while range couldn't be bothered, dict jumped up 
and down shouting, "I want some!"

So now, in Python 3, .keys(), .values(), even .items() all return these 'view' thingies.

And everything I thought I knew about when to use one or the other went out the window.

For example, if you need to modify a dict while iterating over it, use .keys(), right?  Wrong:

--> d = {1: 'one', 2:'two', 3:'three'}
--> for k in d.keys():
...   if k == 1:
...     del d[k]
...
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration


If you need to manipulate the keys (maybe adding some, maybe deleting some) before doing something else with final key 
collection, use .keys(), right?  Wrong:

--> dk = d.keys()
--> dk.remove(2)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'dict_keys' object has no attribute 'remove'


I understand that the appropriate incantation in Python 3 is:

--> for k in list(d)
...    ...

or

--> dk = list(d)
--> dk.remove(2)

which also has the added benefit of working the same way in Python 2.

So, my question boils down to:  in Python 3 how is dict.keys() different from dict?  What are the use cases?

--
~Ethan~



More information about the Python-list mailing list