在Python2.x和Python3.x中dict.keys()的差异

dict.keys()

Python 中字典(Dictionary) , keys() 函数以列表返回一个字典所有的键。

Python2.x和Python3.x有所不同:

python2.x中,dict.keys()返回一个列表

eg:

dict={'name':'ming','age':20}
dict.keys()
Out[67]: ['name', 'age']

python3.x中,dict.keys()返回一个dict_keys对象,比起列表,这个对象的行为更像是集合set,而不是列表list。

解决方案:list(dict.keys())

eg:

dict={'name':'ming','age':20}
dict.keys()
Out[67]: dict_keys(['name', 'age'])
list(dict.keys())
Out[68]: ['name', 'age']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章