本文介绍了Python dictionary.keys()错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用.keys(),而不是获得像这样的键的列表过去一直都有.但是我明白了.

I am trying to use the .keys() and instead of getting a list of the keys like always have in the past. However I get this.

b = { 'video':0, 'music':23 }
k = b.keys()
print( k[0] )

>>>TypeError: 'dict_keys' object does not support indexing

print( k )
dict_keys(['music', 'video'])

除非我发疯,否则它应该只打印['music','video'].

it should just print ['music', 'video'] unless I'm going crazy.

这是怎么回事?

推荐答案

Python 3更改了dict.keys的行为,现在它返回了一个dict_keys对象,该对象是可迭代但不可索引的(就像旧的,现在消失了).您可以通过显式调用list:

Python 3 changed the behavior of dict.keys such that it now returns a dict_keys object, which is iterable but not indexable (it's like the old dict.iterkeys, which is gone now). You can get the Python 2 result back with an explicit call to list:

>>> b = { 'video':0, 'music':23 }
>>> k = list(b.keys())
>>> k
['music', 'video']

或者只是

>>> list(b)
['music', 'video']

这篇关于Python dictionary.keys()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 16:02