0

I am getting below while storing dictionary in heapq. Does anyone know how to solve this ? '<' not supported between instances of 'dict' and 'dict'

import heapq
PQ = []
heapq.heappush(PQ, {"1": "animal"})
heapq.heappush(PQ, {"2": "vechile"})
heapq.heappush(PQ, {"3": "music"})
print(PQ)

heapq.heappush(PQ, {"2": "vechile"})

TypeError: '<' not supported between instances of 'dict' and 'dict'

Community
  • 1
  • 1
Atila
  • 81
  • 4
  • 9
  • Dictionaries don't have any built-in ordering - how could you possibly define such a thing, given that dicts may have arbitrary numbers of keys and values? Perhaps you want to use tuples such as `("1", "animal")`, which do have a defined ordering (first elements are compared, then the second elements if the first were equal, and so on). – jasonharper Jun 22 '19 at 14:18
  • @Atar new, as you seen from comments - dictionaries don't support comparison operators. Elaborate your conditions: 1) can you change the type of input items? 2) are those dicts come from the outer scope? 3) what is the expected result of utilizing heapq in your case ? – RomanPerekhrest Jun 22 '19 at 14:33
  • @RomanPerekhrest basically I am trying to use heapq in diskastra. I was storing it in dictionary format only. – Atila Jun 23 '19 at 10:58

1 Answers1

0

Here are a few options:

  • wrap your dictionaries in a class instance that defines a order over them
  • convert your dictionaries to a type that already has a order

The issue is what does {"1": "animal"} < {"2": "vechile"} mean?

Are the keys actually priorities and the values data in which case shouldn't they be tuples or namedtuples or orderable objects. ("1", "animal") < ("2", "vechile") has a meaning although the ordering of strings of decimals is not the same as the order of their numeric values. This is the "10" < "2" vs 2 < 10 issue.

Dan D.
  • 73,243
  • 15
  • 104
  • 123