0

In Python 2 you can compare dictionaries with the less-than and greater-than operators, meaning that they can be sorted/ordered:

>>> {'a': 2} < {'a': 3}
True
>>> {'a': 7} < {'a': 3}
False
>>> {'b': 4} > {'c': 1}
False
>>> sorted([{'c': 1}, {'a': 5}, {'b':2 }])
[{'a': 5}, {'b': 2}, {'c': 1}]

In Python 3 you cannot do that:

>>> {'a': 2} < {'a': 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'
>>> sorted([{'c': 1}, {'a': 5}, {'b':2 }])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'
  • How are the dictionaries compared in Python 2? (how is the <-operator defined?)
  • And when was this change introduced? (which specific version? And why?)
qff
  • 5,524
  • 3
  • 37
  • 62
  • Not sure if its a duplicate -- of that question atleast – Alan Kavanagh Feb 14 '19 at 13:28
  • At least based on your example, it looks like you compare them item by item, where each item is a tuple consisting of a key and its value. Since there's no guaranteed order in which you would *get* those items, you couldn't reliably compare two dicts. (*Maybe* they would be sorted by key first, but that assumes there is a defined sort order on the keys.) Python 3 probably wisely decided to drop whatever arbitrary ordering was previously used. – chepner Feb 14 '19 at 13:31
  • Also, just like `+`, there are several ways you might consider comparing two dictionaries: by size, by order of their keys, by order of their values, etc. Better to provide *no* built-in support than to pick an implementation arbitrarily. – chepner Feb 14 '19 at 13:33
  • The only answer I know is "Why dict comparison was removed" — I'll quote the OP _"How are the dictionaries compared?"_. – gboffi Feb 14 '19 at 14:12

0 Answers0