通过Python按Python排序顺序迭代 [英] Iterate through Python dictionary by Keys in sorted order

查看:219
本文介绍了通过Python按Python排序顺序迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python中的字典,如下所示:

  D = {1:'a',5:' b',2:'a',7:'a'} 

大多不相关有没有办法通过数字顺序的按键迭代字典?钥匙都是整数。



而不是说

 在D:
#代码...

我可以在订单1,2,5,7?感谢您的帮助。



此外,我无法使用排序/排序的功能。

解决方案

您可以使用以下内容:

 用于排序(D.iterkeys())中的键:
..代码..

在Python 3.x中,使用 D.keys()(与Python 2.x中的 D.iterkeys()相同


I have a dictionary in Python that looks like this:

D = {1:'a', 5:'b', 2:'a', 7:'a'}

The values of the keys are mostly irrelevant. Is there are way to iterate through the dictionary by keys in numerical order? The keys are all integers.

Instead of saying

for key in D:
    # code...

Can I go through the dictionary keys in the order 1, 2, 5, 7? Thanks for your help in advance.

Additionally, I cannot use the sort/sorted functions.

解决方案

You can use this:

for key in sorted(D.iterkeys()):
    .. code ..

In Python 3.x, use D.keys() (which is the same as D.iterkeys() in Python 2.x).

这篇关于通过Python按Python排序顺序迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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