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

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

    In general, one may sort a dict like so:

    for k in sorted(d):
        print k, d[k]
    

    For the specific case in the question, having a "drop in replacement" for d.iteritems(), add a function like:

    def sortdict(d, **opts):
        # **opts so any currently supported sorted() options can be passed
        for k in sorted(d, **opts):
            yield k, d[k]
    

    and so the ending line changes from

    return dict.iteritems()
    

    to

    return sortdict(dict)
    

    or

    return sortdict(dict, reverse = True)
    

提交回复
热议问题