如何在Python中将字典键作为列表返回?
本文翻译自:How to return dictionary keys as a list in Python?
In Python 2.7 , I could get dictionary keys , values , or items as 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中返回列表?
#1楼
参考:https://stackoom.com/question/18ZRm/如何在Python中将字典键作为列表返回
#2楼
Try list(newdict.keys())
. 尝试list(newdict.keys())
。
This will convert the dict_keys
object 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 ). Python的编码方式是假设鸭子输入( 如果看起来像鸭子,而像鸭子一样嘎嘎叫,那就是鸭子 )。 The dict_keys
object will act like a list for most purposes. 在dict_keys
对象的作用类似于列表。 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. 显然,插入运算符可能不起作用,但是对于字典关键字列表而言,这并没有多大意义。
#3楼
A bit off on the "duck typing" definition -- dict.keys()
returns an iterable object, not a list-like object. 在“鸭子类型”定义上dict.keys()
偏离dict.keys()
返回一个可迭代的对象,而不是类似列表的对象。 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...) 列表也是可迭代的,但可迭代的不是列表(或序列...)
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()
. 如果确实需要它们作为列表,则可以调用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']]
#4楼
list(newdict)
works in both Python 2 and Python 3, providing a simple list of the keys in newdict
. list(newdict)
在Python 2和Python 3中均可使用,提供了newdict
中的键的简单列表。 keys()
isn't necessary. keys()
不是必需的。 (: (:
#5楼
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的实现细节)。
#6楼
Converting to a list without using the keys
method 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()
获得少量性能提升 。
如何在Python中将字典键作为列表返回?相关推荐
- 如何在Python中将元素添加到列表
In this tutorial, we will learn different ways to add elements to a List in Python. 在本教程中,我们将学习使用Pyt ...
- python中如何追加_如何在Python中将元素添加到列表中-追加,扩展和插入
在Python中使用列表时,您通常会希望向列表中添加新元素. Python列表数据类型具有三种添加元素的方法:append()-将单个元素追加到列表. extend() -将iterable的元素添加 ...
- python列表可以混合类型_如何在Python中将混合数据类型的列表转换为数据帧
我有一个混合数据类型列表,如下所示:list = [['3D prototypes', 'Can print large objects', 'Autodesk Maya/Mudbox', '3D S ...
- 在Python中将整数附加到列表的开头
本文翻译自:Append integer to beginning of list in Python I have an integer and a list. 我有一个整数和一个列表. I wou ...
- 如何在Python中串联两个列表?
如何在Python中串联两个列表? 例: listone = [1, 2, 3] listtwo = [4, 5, 6] 预期结果: >>> joinedlist [1, 2, 3, ...
- 如何在 Python 中将 Excel 文件转换为图像?Aspose快速搞定
在各种情况下,需要将 Excel 电子表格嵌入到 Web 或桌面应用程序中.在这种情况下的解决方案之一是将 Excel 工作表转换为图像格式.在本文中,将学习如何在 Python中将Excel XLS ...
- python十进制小数转二进制小数,从零开始学Python|如何在Python中将小数转换为二进制...
Python是一种高度通用且功能强大的编程语言.在可以做的许多事情中,从十进制转换为二进制,反之亦然,这是最突出的一项.因此,在本文中,我们将更多地讨论如何在Python中将十进制转换为二进制,反之亦 ...
- python如何创建函数对列表里的元素进行分类_zip()函数如何在python中遍历多个列表?...
在对列表的元素进行找寻时,会频繁的说到遍历的理念.对于复杂的遍历要求,如多个列表中查找就显然不适合用for循环.本篇所要带来的是zip() 函数的方法,能够对多个迭代器进行遍历.下面我们就python ...
- 如何在Python中将一个字符串附加到另一个字符串?
我想要一种有效的方法在Python中将一个字符串附加到另一个字符串. var1 = "foo" var2 = "bar" var3 = var1 + var2 ...
最新文章
- 在 Chrome 开发者工具中调试 node.js
- delphichromiumembedded
- 51系列计算机字长,计算机等级考试之MsOffice练习题第51套
- flowable实战(九)flowable数据库表中流程实例、活动实例、任务实例三者之间关系分析
- 关于discuz 不能全文搜索的问题
- Any-Proxy在线反向代理源码
- 5件最灵异的事~~~~~~~~~~~~~~~~~~转
- Solr7.2.1环境搭建和配置ik中文分词器
- main.cpp first defined here 解决
- JS设置select下拉框默认选中
- 如何高效的开展测试工作?
- 【C++】二分法查找某个数字在数组中的下标
- Web3 是什么?为何应该关注?
- C#输出Word文档
- c语言计算n+nn+nnn+nnnn......---@颜麓
- 【游戏逆向】FPS游戏自瞄透视之堆栈分析
- epoll的ET工作模式和LT工作模式
- openwrt拨号上网设置
- 超级计算机有啥用途,什么是超级计算机及其用途?
- 【React】React——redux