[Tutor] dictionary keys

Peter Otten __peter__ at web.de
Tue Apr 8 23:34:04 CEST 2014


Alex Kleider wrote:

> I've got a fairly large script that uses a dictionary (called 'ipDic')
> each
> value of which is a dictionary which in turn also has values which are
> not
> simple types.
> Instead of producing a simple list,
> """
> ips = ipDic.keys()
> print(ips)
> """
> yields
> """
> dict_keys(['61.147.107.120', '76.191.204.54', '187.44.1.153'])
> """
> 
> Searching my code for 'dict_keys' yields nothing.  I've no idea where it
> comes from.
> 
>>>> 
> 
> Can anyone shed light on why instead of getting the <list I'm expecting>
> I
> get "dict_keys( <list I'm expecting> )"?
> 
> (Using Python3, on Ubuntu  12.4)

That's a change in Python 3 where dict.keys() no longer creates a list, but 
instead creates a view on the underlying dict data thus saving time and 
space. In the rare case where you actually need a list you can explicitly 
create one with

ips = list(ipDic)

> I've been unable to reproduce this behaviour using simpler dictionaries
> which seem to work as I expect:

>>>> d = dict(a=1, b=2, c=3)
>>>> d
> {'a': 1, 'c': 3, 'b': 2}
>>>> d.keys()
> ['a', 'c', 'b']
>>>> print(d.keys())
> ['a', 'c', 'b']

That's because the above is a session using Python 2. Compare:

$ python3
Python 3.3.2+ (default, Feb 28 2014, 00:52:16) 
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dict(a=1, b=2).keys()
dict_keys(['b', 'a'])

$ python2
Python 2.7.5+ (default, Feb 27 2014, 19:37:08) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dict(a=1, b=2).keys()
['a', 'b']

PS: You can get a view in Python 2, too, with dict.viewkeys()



More information about the Tutor mailing list