使用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])

如何使用Python 3获得一个简单的键列表?


当前回答

如果你需要单独存储键,这里有一个解决方案,使用扩展可迭代解包(Python3.x+),它需要的输入比迄今为止提出的其他解决方案都要少:

newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict

k
# [1, 2, 3]

Operation no. Of characters
k = list(d) 9 characters (excluding whitespace)
k = [*d] 6 characters
*k, = d 5 characters

其他回答

在不使用keys方法的情况下转换为列表使其更具可读性:

list(newdict)

并且,当循环遍历字典时,不需要key ():

for key in newdict:
    print key

除非你在循环中修改它,这需要事先创建一个键列表:

for key in list(newdict):
    del newdict[key]

在Python 2上,使用keys()会有一个边际的性能提升。

这是在一行代码中获得key List的最佳方法

dict_variable = {1:"a",2:"b",3:"c"}  
[key_val for key_val in dict_variable.keys()]

是的,在python3中有一个更好和最简单的方法来做到这一点。X


使用inbuild list()函数

#Devil
newdict = {1:0, 2:0, 3:0}
key_list = list(newdict)
print(key_list) 
#[1, 2, 3] 

你也可以使用列表推导式:

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

或者,短,

>>> [k  for  k in  newdict]
[1, 2, 3]

注意:在3.7以下的版本中不保证排序(排序仍然只是CPython 3.6的一个实现细节)。

list(newdict)在Python 2和Python 3中都可以使用,在newdict中提供一个简单的键列表。Keys()不是必需的。