如何在Python中将字典键作为列表返回? [英] How to return dictionary keys as a list in Python?

查看:101
本文介绍了如何在Python中将字典键作为列表返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.7 中,我可以将字典 keys values items 作为列表: /p>

In Python 2.7, I could get dictionary keys, values, or items as a list:

>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]

现在,在 Python> = 3.3 中,我得到了类似的内容:

Now, in Python >= 3.3, I get something like this:

>>> newdict.keys()
dict_keys([1, 2, 3])

所以,我必须这样做以获得列表:

So, I have to do this to get a list:

newlist = list()
for i in newdict.keys():
    newlist.append(i)

我想知道,有没有更好的方法可以在 Python 3 中返回列表?

I'm wondering, is there a better way to return a list in Python 3?

推荐答案

尝试list(newdict.keys()).

这会将dict_keys对象转换为列表.

This will convert the dict_keys object to a list.

另一方面,您应该问自己是否重要. Python的编码方式是假设鸭子类型(如果它看起来像鸭子,而像鸭子一样嘎嘎叫,那就是鸭子). dict_keys对象在大多数情况下都将类似于列表.例如:

On the other hand, you should ask yourself whether or not it matters. The Pythonic way to code is to assume duck typing (if it looks like a duck and it quacks like a duck, it's a duck). The dict_keys object will act like a list for most purposes. For instance:

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

很显然,插入运算符可能不起作用,但是对于字典关键字列表而言,这并没有多大意义.

Obviously, insertion operators may not work, but that doesn't make much sense for a list of dictionary keys anyway.

这篇关于如何在Python中将字典键作为列表返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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