Python:获取字典的键 [英] python: getting keys of a dictionary

查看:127
本文介绍了Python:获取字典的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在python3中执行dict.keys()时,我没有得到列表,但得到了dict_keys类的对象。为什么会这样,该对象该怎么办?

When I do dict.keys() in python3, I do not get a list, but an object of class dict_keys. Why is this and what can I do with this object? How to get the list?

示例代码: type(dict(sape = 4139,guido = 4127,jack = 4098).keys() )
我想知道这个结果是否是故意的,为什么?
我打电话给matplotlib.plot(d.keys(),....)并报错。

Example code: type(dict(sape=4139, guido=4127, jack=4098).keys()) I wonder if this result is intentional and why? I called matplotlib.plot(d.keys(),....) and got an error.

推荐答案

dict.keys 返回一个 dict_keys 对象,它是一个可迭代的对象。

dict.keys returns a dict_keys object, which is an iterable object.

因此,您可以使用以下命令将其转换为列表:

So, you can either convert it to a list using:

keys = list(dict.keys())

或者,您可以简单地遍历 dict_keys 对象,如预期的那样:

Or, you can simply iterate over the dict_keys object, like it was intended:

for key in dict.keys():
    print(key)

在您的示例中,它将打印出:

In your example, it will print out:

sape
guido
jack

这篇关于Python:获取字典的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆