尚未对此进行广泛的测试,但是可以在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}
>>> for key, value in sorted(d.iteritems()):
>>> print(key, value)
('a', 2222)
('h', 15)
('x', 2)
>>>
在Python 3.x中,使用d.items()
代替d.iteritems()
返回迭代器。