蟒蛇字典.keys()错误
【腾讯云】亏本大甩卖,服务器4核16G 1年370元(带宽12M,系统盘120GB SSD盘,月流量2000GB)!!!!!!
云产品 配置 价格
服务器 1核2G,带宽5M,系统盘50GB SSD盘,月流量500GB 38元/年
MySQL 1核1G 19元/年
服务器 16核32G,带宽18M,系统盘250GB SSD盘,月流量5000GB 1197元/年
点我进入腾讯云,查看更多详情

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

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

What's going on?

#0

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']

or just

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

#1

If you assigned k like so:

k = list(b.keys())

your code will work.

As the error says, the dict_keys type does not support indexing.

#2

This is one of the breaking changes between Python 2 and 3.

In Python 2:

>>> help(dict.keys)
keys(...)
    D.keys() -> list of D's keys

In Python 3:

>>> help(dict.keys)
keys(...)
    D.keys() -> a set-like object providing a view on D's keys

This change in behavior makes a lot of sense since a dict is semantically unordered and its keys are unique - just like a set.

This change means that you don't have to create a new list of keys every time you want to do some kind of set comparison with a dict's keys.

Getting the same behavior in 2 and 3

To help transition to Python 3, Python 2.7 has another dict method, viewkeys. The viewkeys method is most similar to Python 3's dict.keys method:

>>> d
{'a': None, 'c': None, 'b': None, 'd': None}
>>> for k in d.viewkeys(): print k
... 
a
c
b
d
>>> d.viewkeys() & set('abc')
set(['a', 'c', 'b'])

In Python 3, the closest analog to the old behavior is to pass dict.keys() to list:

>>> d
{'d': None, 'a': None, 'c': None, 'b': None}
>>> list(d.keys())
['d', 'a', 'c', 'b']

Or just pass the dict to list, since a dict will iterate over its keys anyways:

>>> list(d)
['d', 'a', 'c', 'b']

You could create a utility functions to abstract the behavior over 2 and 3:

if hasattr(dict, 'viewkeys'): # Python 2.7
    def keys(d):
        return d.viewkeys()
else:  # Python 3
    def keys(d):
        return d.keys()

And pass a dict to list to get the list form, and in both 2 and 3, you'll get the same output:

>>> d
{'b': None, 'a': None, 'c': None, 'd': None}
>>> keys(d)
dict_keys(['b', 'a', 'c', 'd'])
>>> list(d)
['b', 'a', 'c', 'd']

#3

If you simply want a list of keys from a dictionary you can directly do like this:

b = {"name": "xyz", "class":"abc", "college": "qwert"}  
key_list = list(b)

key_list will contain all the key names as a list, though, this will not repeats a key, if found more than once. Duplicate keys will be counted as one.

推荐文章

如何访问R。字符串.xxx通过将字符串“xxx”作为参数传递给方法的资源?

如何访问R。字符串.xxx通过将字符串“xxx”作为参数传递给方法的资源?

推荐文章

Regexp在emacs的URL后面去掉字符

Regexp在emacs的URL后面去掉字符

推荐文章

Ajax工具包日历扩展程序加粗当前日期,ASP.NET

Ajax工具包日历扩展程序加粗当前日期,ASP.NET

推荐文章

奇怪的Adobe炼金术编译器失败

奇怪的Adobe炼金术编译器失败

推荐文章

asp.netajxa RadEditor问题

asp.netajxa RadEditor问题

推荐文章

将数据/内容下载到Sqlite数据库

将数据/内容下载到Sqlite数据库

推荐文章

从Oracle迁移到MySQL或PostgreSQL

从Oracle迁移到MySQL或PostgreSQL

推荐文章

如何将数组传递给其他活动?

如何将数组传递给其他活动?

推荐文章

哪些iOS设备支持哪个版本的Open GL ES

哪些iOS设备支持哪个版本的Open GL ES

推荐文章

即使字段不在CakePHP中,是否可以强制表单帮助器根据需要呈现该字段?

即使字段不在CakePHP中,是否可以强制表单帮助器根据需要呈现该字段?

推荐文章

Android/Eclispe:如何在设备或模拟器上以发布模式运行我的应用程序?(如果有…)

Android/Eclispe:如何在设备或模拟器上以发布模式运行我的应用程序?(如果有…)

推荐文章

Windows Phone 7-将内容移动到键盘上方

Windows Phone 7-将内容移动到键盘上方

推荐文章

使用rake转储和加载数据库

使用rake转储和加载数据库

推荐文章

使用回调和持久变量在MATLAB中连续获取数据

使用回调和持久变量在MATLAB中连续获取数据

推荐文章

iOS视网膜显示:“@2x”支持jpeg和png吗?

iOS视网膜显示:“@2x”支持jpeg和png吗?

推荐文章

jQuery选择具有类A、类B或类C的元素

jQuery选择具有类A、类B或类C的元素