前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何在Python中将字典键作为列表返回?

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

作者头像
用户7886150
修改2021-01-25 10:29:39
2.1K0
修改2021-01-25 10:29:39
举报
文章被收录于专栏:bit哲学院

参考链接: Python字典keys()

本文翻译自: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()获得少量性能提升 。

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档