在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']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章