LNA
LNA

Reputation: 1447

Elementary python confusion from free online book I'm reading

I'm reading http://interactivepython.org/courselib/static/pythonds/Introduction/introduction.html#review-of-basic-python.

If adict is a dictionary, then adict.keys() returns the keys of the dictionary in a dict_keys object. However, I just tried this in a Python shell:

>>> a = {'a': 1, 'b': 2}
>>> a
{'a': 1, 'b': 2}
>>> a.keys()
['a', 'b']
>>> list(a.keys())
['a', 'b']

And the book says that if I type a.keys(), it should return dict_items['a','b'] instead of just ['a','b']. Why is that?

Upvotes: 0

Views: 40

Answers (2)

user2555451
user2555451

Reputation:

Your book was written for Python 3.x but you are using Python 2.x.

In Python 3.x only, dict.keys returns a dictionary view object of a dictionary's keys (or what you called a dict_keys object):

>>> # Python 3.x interpreter
>>> a = {'a': 1, 'b': 2}
>>> a.keys()
dict_keys(['b', 'a'])
>>>

In Python 2.x however, the method simply returns a list of the keys.

>>> # Python 2.x interpreter
>>> a = {'a': 1, 'b': 2}
>>> a.keys()
['b', 'a']
>>>

You need to use dict.viewkeys to get a dictionary view object like in Python 3.x:

>>> # Python 2.x interpreter
>>> a = {'a': 1, 'b': 2}
>>> a.viewkeys()
dict_keys(['a', 'b'])
>>>

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304127

Your book is using Python3

$ 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.
>>> a = {'a': 1, 'b': 2}
>>> a.keys()
dict_keys(['a', 'b'])
>>> a.items()
dict_items([('a', 1), ('b', 2)])

In python2, a list is returned instead of these new dict_keys and dict_items objects

Since the book is using Python3, you should probably go ahead and install that alongside your Python2 to try out their examples or you'll have more problems like this down the track

Upvotes: 1

Related Questions