在Python中,如何按已排序的键顺序遍历字典? [英] In Python, how do I iterate over a dictionary in sorted key order?
问题描述
有一个现有的函数以下面的结尾,其中d
是一个字典:
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?
推荐答案
此功能尚未进行广泛测试,但可以在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)
>>>
如果您习惯于使用for key, value in 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 3.x,使用d.items()
而不是d.iteritems()
返回迭代器.
With Python 3.x, use d.items()
instead of d.iteritems()
to return an iterator.
这篇关于在Python中,如何按已排序的键顺序遍历字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!