In Python, how do I iterate over a dictionary in sorted key order?

后端 未结 10 1009
有刺的猬
有刺的猬 2020-11-27 10:19

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

return d.iteritems()

that returns an unsort

10条回答
  •  忘掉有多难
    2020-11-27 11:03

    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.

提交回复
热议问题