在Python中,如何以排序顺序迭代字典? [英] In Python, how do I iterate over a dictionary in sorted order?

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

问题描述

有一个现有的功能结束于:

There's an existing function that ends in:

return dict.iteritems()

返回给定字典的未排序迭代器。我想返回一个按排序顺序排列的项目的迭代器。如何做到这一点?

that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that?

推荐答案

没有非常广泛地测试,但在Python 2.5.2中可以工作。 >

Haven't tested this very extensively, but works in Python 2.5.2.

>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>

如果您习惯为密钥执行,则在d.iteritems ):... 而不是迭代器,这仍然适用于上述解决方案

If you are used to doing for key, value in d.iteritems(): ... instead of iterators, this will still work with the solution above

>>> d = {"x":2, "h":15, "a":2222}
>>> for key, value in sorted(d.iteritems()):
>>>     print(key, value)
('a', 2222)
('h', 15)
('x', 2)
>>>

这篇关于在Python中,如何以排序顺序迭代字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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