如何在 Python 中将字典键作为列表返回?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16819222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return dictionary keys as a list in Python?
提问by
In Python 2.7, I could get dictionary keys, values, or itemsas a list:
在Python 2.7 中,我可以将字典键、值或项目作为列表获取:
>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]
Now, in Python >= 3.3, I get something like this:
现在,在Python >= 3.3 中,我得到如下信息:
>>> 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?
我想知道,有没有更好的方法来返回Python 3 中的列表?
采纳答案by Chris
Try list(newdict.keys()).
试试list(newdict.keys())。
This will convert the dict_keysobject to a list.
这会将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_keysobject will act like a list for most purposes. For instance:
另一方面,你应该问问自己这是否重要。Pythonic 的编码方式是假设鸭子类型(如果它看起来像一只鸭子并且叫起来像一只鸭子,它就是一只鸭子)。在dict_keys大多数情况下,该对象将像一个列表一样。例如:
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.
显然,插入运算符可能不起作用,但无论如何这对于字典键列表没有多大意义。
回答by Chris Barker
A bit off on the "duck typing" definition -- dict.keys()returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)
有点偏离“鸭子类型”的定义——dict.keys()返回一个可迭代对象,而不是一个类似列表的对象。它可以在可迭代的任何地方工作——而不是列表可以工作的任何地方。一个列表也是一个可迭代的,但一个可迭代的不是一个列表(或序列......)
In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list().
在实际用例中,对 dict 中的键做的最常见的事情是遍历它们,所以这是有道理的。如果您确实需要它们作为列表,您可以调用list().
Very similarly for zip()-- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?
非常相似zip()——在绝大多数情况下,它是迭代的——为什么要创建一个全新的元组列表来迭代它然后再把它扔掉?
This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.
这是 Python 中使用更多迭代器(和生成器)而不是到处复制列表的大趋势的一部分。
dict.keys()should work with comprehensions, though -- check carefully for typos or something... it works fine for me:
dict.keys()不过,应该与理解一起工作 - 仔细检查拼写错误或其他东西......它对我来说很好:
>>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
>>> [key.split(", ") for key in d.keys()]
[['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]
回答by Seb
list(newdict)works in both Python 2 and Python 3, providing a simple list of the keys in newdict. keys()isn't necessary. (:
list(newdict)适用于 Python 2 和 Python 3,提供了一个简单的newdict. keys()没有必要。(:
回答by u5844373
You can also use a list comprehension:
您还可以使用列表理解:
>>> newdict = {1:0, 2:0, 3:0}
>>> [k for k in newdict.keys()]
[1, 2, 3]
Or, shorter,
或者,更短,
>>> [k for k in newdict]
[1, 2, 3]
Note: Order is not guaranteed on versions under 3.7 (ordering is still only an implementation detail with CPython 3.6).
注意:3.7 以下的版本不保证顺序(顺序仍然只是 CPython 3.6 的一个实现细节)。
回答by Cas
Converting to a list without using the keysmethod makes it more readable:
不使用该keys方法转换为列表使其更具可读性:
list(newdict)
and, when looping through dictionaries, there's no need for keys():
并且,在循环字典时,不需要keys():
for key in newdict:
print key
unless you are modifying it within the loop which would require a list of keys created beforehand:
除非您在循环中修改它,这需要预先创建的键列表:
for key in list(newdict):
del newdict[key]
On Python 2 there is a marginal performance gain using keys().
在 Python 2 上,使用keys().
回答by Dimitris Fasarakis Hilliard
Python >= 3.5 alternative: unpack into a list literal[*newdict]
Python >= 3.5 替代方案:解压成列表文字[*newdict]
New unpacking generalizations (PEP 448)were introduced with Python 3.5 allowing you to now easily do:
Python 3.5 引入了新的解包概括 (PEP 448),现在您可以轻松地执行以下操作:
>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]
Unpacking with *works with anyobject that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.
解包*适用于任何可迭代的对象,并且由于字典在迭代时返回它们的键,因此您可以通过在列表文字中使用它来轻松创建列表。
Adding .keys()i.e [*newdict.keys()]might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should reallybe worried about).
添加.keys()ie[*newdict.keys()]可能有助于使您的意图更加明确,尽管它会花费您一次函数查找和调用。(老实说,这不是您真正应该担心的事情)。
The *iterablesyntax is similar to doing list(iterable)and its behaviour was initially documented in the Calls sectionof the Python Reference manual. With PEP 448 the restriction on where *iterablecould appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression listswas also updated to state this.
该*iterable语法类似于做list(iterable)其行为最初记录在呼叫部分Python的参考手册。PEP 448 放宽了对*iterable出现位置的限制,允许它也被放置在列表、集合和元组文字中,关于表达式列表的参考手册也被更新以说明这一点。
Though equivalent to list(newdict)with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:
虽然相当于list(newdict)它更快(至少对于小字典)的区别,因为实际上没有执行函数调用:
%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop
%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop
%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop
with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).
对于较大的字典,速度几乎相同(迭代大型集合的开销胜过函数调用的小成本)。
In a similar fashion, you can create tuples and sets of dictionary keys:
以类似的方式,您可以创建元组和字典键集:
>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}
beware of the trailing comma in the tuple case!
当心元组案例中的尾随逗号!
回答by cs95
If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking(python3.x+).
如果您需要单独存储密钥,这里有一个解决方案,该解决方案使用扩展可迭代解包(python3.x+) ,比迄今为止提供的所有其他解决方案需要更少的输入。
newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict
k
# [1, 2, 3]
╒═══════════════╤═════════════════════════════════════════╕
│ k = list(d) │ 9 characters (excluding whitespace) │
├───────────────┼─────────────────────────────────────────┤
│ k = [*d] │ 6 characters │
├───────────────┼─────────────────────────────────────────┤
│ *k, = d │ 5 characters │
╘═══════════════╧═════════════════════════════════════════╛
回答by Rahul
I can think of 2 ways in which we can extract the keys from the dictionary.
我可以想到两种方法来从字典中提取键。
Method 1: -To get the keys using .keys() method and then convert it to list.
方法 1: -使用 .keys() 方法获取密钥,然后将其转换为列表。
some_dict = {1: 'one', 2: 'two', 3: 'three'}
list_of_keys = list(some_dict.keys())
print(list_of_keys)
-->[1,2,3]
Method 2: -To create an empty list and then append keys to the list via a loop. You can get the values with this loop as well (use .keys() for just keys and .items() for both keys and values extraction)
方法 2: -创建一个空列表,然后通过循环将键附加到列表中。您也可以使用此循环获取值(仅将 .keys() 用于键,将 .items() 用于键和值提取)
list_of_keys = []
list_of_values = []
for key,val in some_dict.items():
list_of_keys.append(key)
list_of_values.append(val)
print(list_of_keys)
-->[1,2,3]
print(list_of_values)
-->['one','two','three']

