在 Python 中,如何按排序的键顺序遍历字典? [英] In Python, how do I iterate over a dictionary in sorted key order?

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

问题描述

有一个以以下结尾的现有函数,其中 d 是一个字典:

返回 d.iteritems()

返回给定字典的未排序迭代器.我想返回一个迭代器,它遍历按键排序的项目.我该怎么做?

解决方案

尚未对此进行广泛测试,但可在 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)>>>

如果你习惯用 for key, value in d.iteritems(): ... 而不是迭代器,这仍然适用于上面的解决方案

<预><代码>>>>d = {"x":2, "h":15, "a":2222}>>>对于键,排序(d.iteritems())中的值:>>>打印(键,值)('a', 2222)('h', 15)('x', 2)>>>

对于 Python 3.x,使用 d.items() 而不是 d.iteritems() 来返回迭代器.

There's an existing function that ends in the following, where d is a dictionary:

return d.iteritems()

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

解决方案

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

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

With Python 3.x, use d.items() instead of d.iteritems() to return an iterator.

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

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