Dictionaries cannot be ordered, so you need to create something that the dictionary can contain, but not use it in comparison.
Tuples are not a good choice, because each element of them can be compared. For example, if the first element (yours key) is equal, then the second element is compared:
>>> (1, {'a': 1}) < (1, {'a': 2})
TypeError: unorderable types: dict() < dict()
Or with heap:
>>> heap = []
>>> heapq.heappush(heap, (2, {'a': 1}))
>>> heapq.heappush(heap, (2, {'b': 2}))
TypeError: unorderable types: dict() < dict()
key , , .
dict, , (key, value), - key:
from functools import total_ordering
@total_ordering
class KeyDict(object):
def __init__(self, key, dct):
self.key = key
self.dct = dct
def __lt__(self, other):
return self.key < other.key
def __eq__(self, other):
return self.key == other.key
def __repr__(self):
return '{0.__class__.__name__}(key={0.key}, dct={0.dct})'.format(self)
heap, , dict :
>>> import heapq
>>> heap = []
>>> heapq.heappush(heap, KeyDict(2, {'a': 1}))
>>> heapq.heappush(heap, KeyDict(2, {'b': 2}))
>>> heap
[KeyDict(key=2, dct={'a': 1}), KeyDict(key=2, dct={'b': 2})]
3 , , dict:
>>> from itertools import count
>>> cnt = count()
>>> heap = []
>>> heapq.heappush(heap, (2, next(cnt), {'a': 1}))
>>> heapq.heappush(heap, (2, next(cnt), {'b': 2}))
>>> heap
[(2, 0, {'a': 1}), (2, 1, {'b': 2})]