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

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

问题描述

Python 2.7中,我可以将字典作为列表:

<预><代码>>>>新字典 = {1:0, 2:0, 3:0}>>>newdict.keys()[1, 2, 3]

现在,在 Python >= 3.3 中,我得到了这样的结果:

<预><代码>>>>newdict.keys()dict_keys([1, 2, 3])

所以,我必须这样做才能得到一个列表:

newlist = list()对于 newdict.keys() 中的 i:newlist.append(i)

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

解决方案

试试list(newdict.keys()).

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

另一方面,你应该问问自己这是否重要.Pythonic 的编码方式是假设鸭子类型(如果它看起来像一只鸭子并且叫起来像一只鸭子,它就是一只鸭子).在大多数情况下,dict_keys 对象就像一个列表.例如:

 用于 newdict.keys() 中的键:打印(键)

显然,插入运算符可能不起作用,但无论如何这对于字典键列表没有多大意义.

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]

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)

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

解决方案

Try list(newdict.keys()).

This will convert the dict_keys object to a list.

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天全站免登陆