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

后端 未结 10 1014
有刺的猬
有刺的猬 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 10:54

    You can now use OrderedDict in Python 2.7 as well:

    >>> from collections import OrderedDict
    >>> d = OrderedDict([('first', 1),
    ...                  ('second', 2),
    ...                  ('third', 3)])
    >>> d.items()
    [('first', 1), ('second', 2), ('third', 3)]
    

    Here you have the what's new page for 2.7 version and the OrderedDict API.

提交回复
热议问题