1

I am trying to test the following:

IN Python 2.x, sorted works fine:

>>> sorted([{'callme': 'voyaps-ai-job', 'breakme': 'folld-qy'}, {'callme': 'mixerjui', 'breakme': 'folld-ry'}, {'callme': 'voyaps-ml-jobs', 'breakme': 'folld-uy'}])
[{'breakme': 'folld-qy', 'callme': 'voyaps-ai-job'}, {'breakme': 'folld-ry', 'callme': 'mixerjui'}, {'breakme': 'folld-uy', 'callme': 'voyaps-ml-jobs'}]

In 3.X this breaks

>>> sorted([{'callme': 'voyaps-ai-job', 'breakme': 'folld-qy'}, {'callme': 'mixerjui', 'breakme': 'folld-ry'}, {'callme': 'voyaps-ml-jobs', 'breakme': 'folld-uy'}])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'

i.e i cannot call sorted on this kind of data. what can i do to accomplish this ?

Nishant Singh
  • 3,055
  • 11
  • 36
  • 74
  • 1
    You can pass a `key` to indicate how you would like these objects to be sorted. – khelwood Feb 06 '19 at 09:56
  • https://stackoverflow.com/questions/22333388/dicts-are-not-orderable-in-python-3 – HarryClifton Feb 06 '19 at 09:57
  • Python 3 dictionaries have some subtle differences, like in the link Suraj added. Python 2 tries to make everything orderable, Python 3 only supports ordering to numbers and strings by default, where else you'll have to *provide* the way you want the sort to work, like `sorted(mydict, key=lambda x:sorted(x.keys()))` – hyperTrashPanda Feb 06 '19 at 10:04

1 Answers1

6

It makes no real sense to use < on two dictionaries. Python 2 didn't care and it just guessed something (sorted on memory address or so), Python 3 is stricter.

You have to specify what you mean with sorting dictionaries. When should a dictionary sort before another?

If you want it to depend on e.g. the value for the key 'callme', then you could do

sorted([{'callme': 'voyaps-ai-job', 'breakme': 'folld-qy'}, {'callme': 'mixerjui', 'breakme': 'folld-ry'}, {'callme': 'voyaps-ml-jobs', 'breakme': 'folld-uy'}],
      key=lambda d: d['callme'])
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79