Neat way of popping key, value PAIR from dictionary?

后端 未结 3 1441
粉色の甜心
粉色の甜心 2021-01-18 03:20

pop is a great little function that, when used on dictionaries (given a known key) removes the item with that key from the dictionary and also returns the corre

3条回答
  •  终归单人心
    2021-01-18 04:20

    A heap supports the pop-min operation you describe. You'll need to create a heap from your dictionary first, though.

    import heapq
    # Must be two steps; heapify modifies its argument in-place.
    # Reversing the key and the value because the value will actually be
    # the "key" in the heap. (Or rather, tuples are compared 
    # lexicographically, so put the value in the first position.)
    heap = [(v, k) for k, v in some_dict.items()]
    heapq.heapify(heap)
    
    # Get the smallest item from the heap
    value, key = heapq.heappop(heap)
    

提交回复
热议问题