python字典顺序遍历_在Python中,如何按已排序的键顺序遍历字典?
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字典顺序遍历_在Python中,如何按已排序的键顺序遍历字典?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 韩媒:中国厂商瞄准印度智能手机市场 发起
- 下一篇: 拼多多怎么设置让别人看不见你买的东西