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

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

    Use the sorted() function:

    return sorted(dict.iteritems())
    

    If you want an actual iterator over the sorted results, since sorted() returns a list, use:

    return iter(sorted(dict.iteritems()))
    

提交回复
热议问题