Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

python - 如何在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中返回列表?)

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(显然,插入运算符可能不起作用,但是对于字典关键字列表而言,这并没有多大意义。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...