且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字典键作为Python中的列表返回

更新时间:2023-01-21 22:31:24

尝试 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.