是否有“单线”?从排序顺序获取字典中的键列表的方法? [英] Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

查看:139
本文介绍了是否有“单线”?从排序顺序获取字典中的键列表的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表 sort()方法是一个修饰符函数,它返回

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()

,我必须:

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?

推荐答案

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)

这篇关于是否有“单线”?从排序顺序获取字典中的键列表的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆