Python 免费在线图书I';我在读书

Python 免费在线图书I';我在读书,python,dictionary,Python,Dictionary,我在看书 如果adict是字典,则adict.keys()在dict\u keys对象中返回字典的键。但是,我只是在Python shell中尝试了这一点: >>> a = {'a': 1, 'b': 2} >>> a {'a': 1, 'b': 2} >>> a.keys() ['a', 'b'] >>> list(a.keys()) ['a', 'b'] 这本书说如果我输入a.keys(),它应该返回dict_item

我在看书

如果
adict
是字典,则
adict.keys()
dict\u keys
对象中返回字典的键。但是,我只是在Python shell中尝试了这一点:

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

这本书说如果我输入
a.keys()
,它应该返回
dict_items['a','b']
,而不仅仅是
['a','b']
。为什么会这样?

您的书是为Python 3.x编写的,但您使用的是Python 2.x

仅在Python3.x中,返回字典键(或您称之为
dict_keys
对象)的值:

然而,在Python2.x中,该方法只返回一个键列表

>>> # Python 2.x interpreter
>>> a = {'a': 1, 'b': 2}
>>> a.keys()
['b', 'a']
>>>
您需要使用来获取类似Python 3.x中的dictionary视图对象:

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

你的书正在使用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)])
在python2中,返回一个
列表
,而不是这些新的
dict_键
dict_项
对象

因为这本书使用的是Python3,所以您可能应该继续将其与Python2一起安装,以尝试它们的示例,否则您会遇到更多类似的问题

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