Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #51114

Python 3: dict & dict.keys()

Date 2013-07-23 18:16 -0700
From Ethan Furman <ethan@stoneleaf.us>
Subject Python 3: dict & dict.keys()
Newsgroups comp.lang.python
Message-ID <mailman.5024.1374628577.3114.python-list@python.org> (permalink)

Show all headers | View raw


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~

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Python 3: dict & dict.keys() Ethan Furman <ethan@stoneleaf.us> - 2013-07-23 18:16 -0700
  Re: Python 3: dict & dict.keys() Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-07-24 02:11 +0000
    Re: Python 3: dict & dict.keys() Ian Kelly <ian.g.kelly@gmail.com> - 2013-07-24 09:02 -0600
    Re: Python 3: dict & dict.keys() Ethan Furman <ethan@stoneleaf.us> - 2013-07-24 17:59 -0700
      Re: Python 3: dict & dict.keys() Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-07-25 05:57 +0000
    Re: Python 3: dict & dict.keys() Ben Finney <ben+python@benfinney.id.au> - 2013-07-25 12:20 +1000

csiph-web