Is there a “one-liner” way to get a list of keys from a dictionary in sorted order?

落爺英雄遲暮 提交于 2019-12-05 02:32:55

问题


The list sort() method is a modifier function that returns None.

So if I want to iterate through all of the keys in a dictionary I cannot do:

for k in somedictionary.keys().sort():
    dosomething()

Instead, I must:

keys = somedictionary.keys()
keys.sort()
for k in keys:
    dosomething()

Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps?


回答1:


for k in sorted(somedictionary.keys()):
    doSomething(k)

Note that you can also get all of the keys and values sorted by keys like this:

for k, v in sorted(somedictionary.iteritems()):
   doSomething(k, v)



回答2:


Can I answer my own question?

I have just discovered the handy function "sorted" which does exactly what I was looking for.

for k in sorted(somedictionary.keys()):
    dosomething()

It shows up in Python 2.5 dictionary 2 key sort




回答3:


Actually, .keys() is not necessary:

for k in sorted(somedictionary):
    doSomething(k)

or

[doSomethinc(k) for k in sorted(somedict)]


来源:https://stackoverflow.com/questions/327191/is-there-a-one-liner-way-to-get-a-list-of-keys-from-a-dictionary-in-sorted-ord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!