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

后端 未结 10 1015
有刺的猬
有刺的猬 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条回答
  •  猫巷女王i
    2020-11-27 10:48

    >>> import heapq
    >>> d = {"c": 2, "b": 9, "a": 4, "d": 8}
    >>> def iter_sorted(d):
            keys = list(d)
            heapq.heapify(keys) # Transforms to heap in O(N) time
            while keys:
                k = heapq.heappop(keys) # takes O(log n) time
                yield (k, d[k])
    
    
    >>> i = iter_sorted(d)
    >>> for x in i:
            print x
    
    
    ('a', 4)
    ('b', 9)
    ('c', 2)
    ('d', 8)
    

    This method still has an O(N log N) sort, however, after a short linear heapify, it yields the items in sorted order as it goes, making it theoretically more efficient when you do not always need the whole list.

提交回复
热议问题