在 Python 中,如何按排序的键顺序遍历字典? [英] In Python, how do I iterate over a dictionary in sorted key order?
问题描述
有一个以以下结尾的现有函数,其中 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(): ...
而不是迭代器,这仍然适用于上面的解决方案
对于 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屋!