[Tutor] dictionary keys

Alex Kleider akleider at sonic.net
Wed Apr 9 02:07:27 CEST 2014


On 2014-04-08 14:34, Peter Otten wrote:

> 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)
> 

> 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()
> 

Thanks, Peter, for this clarification.  I want to present the list 
sorted so probably this is the rare case of which you spoke where I 
would need to use l = list(myDict) rather than the view.


More information about the Tutor mailing list