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

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

问题描述

我注意到,与Python <3> 相比,Python 2.7 和旧版本的Python 3 有所不同。






以前在Python 2.7 中,我可以获得字典 项目作为列表:

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

Python> = 3.3 我得到这样的东西:

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

所以我必须这样做来获取列表:

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






我想知道有没有更好的方法来返回Python 3中的列表?

解决方案

尝试 list(newdict.keys()) p>

这将把dict_keys对象转换成一个列表。



另一方面,你应该问自己这很重要Pythonic的代码方式是假设鸭子打字(如果它看起来像一只鸭子,它像鸭子一样,这是鸭子)。 dict_keys对象将作为大多数用途的列表。例如:

  for newdict.keys():
print(key)

显然,插入运算符可能无法正常工作,但是对于字典键列表来说,这无关紧要。


I have noticed a difference in Python 2.7 and old versions of Python 3 compared to Python >= 3.3.


Previously 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 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 am wondering if there is a better way to return a list in Python 3?

解决方案

Try list(newdict.keys()).

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