Inserting dictionary to heap Python

后端 未结 3 2071
遥遥无期
遥遥无期 2021-01-13 18:17

I\'m trying to build a heap with (key, value) so the key is a number and the value is a dictionary.

import heapq
heap = []
dic = {\'val_1\': \'number_1\', \'         


        
3条回答
  •  走了就别回头了
    2021-01-13 18:57

    So I did a bit of testing and even though you didn't show your full code it would seem that your code is pushing to the heap more than one dict.

    >>> heapq.heappush(heap, (0,dic))
    >>> heapq.heappush(heap, (0,dic2))
    Traceback (most recent call last):
      File "python", line 1, in 
    TypeError: unorderable types: dict() < dict()
    

    Your heap is comparing the dictionaries because the first item of the list has been compared and so it proceeds to compare the next item, instead you need to do something like:

    >>> heapq.heappush(heap, (0,dic))
    >>> heapq.heappush(heap, (1,dic))
    >>> show_tree(heap)
    
    (0, {'val_1': 'number_1', 'val_2': 'number_2', 'val_3': 'number_3'})
    (1, {'val_1': 'number_1', 'val_2': 'number_2', 'val_3': 'number_3'})
    ------------------------------------
    

提交回复
热议问题