1

I have an list of ordereddict of tuples

[
    OrderedDict([('id', 7), ('info', 'info_data')]),
    OrderedDict([('id', 5), ('info', 'info_data')]),
    OrderedDict([('id', 6), ('info', 'info_data')]),
    OrderedDict([('id', 8), ('info', 'info_data')])
]

It is possible to sort by 'id' it and receive next list or ordereddict

[
    OrderedDict([('id', 5), ('info', 'info_data')]),
    OrderedDict([('id', 6), ('info', 'info_data')]),
    OrderedDict([('id', 7), ('info', 'info_data')]),
    OrderedDict([('id', 8), ('info', 'info_data')])
]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Beliaf
  • 577
  • 2
  • 8
  • 25
  • You don't have tuples. That's just the standard display for `OrderedDict` objects, which allows you to easily re-create the same values. You can sort these exactly the same way you'd sort a list of regular dictionaries. – Martijn Pieters Nov 16 '17 at 11:29
  • As a new list: `sorted(list_to_be_sorted, key=lambda k: k['id'])` – Martijn Pieters Nov 16 '17 at 11:30
  • I tried your version have error `TypeError: list indices must be integers or slices, not str` – Beliaf Nov 16 '17 at 11:38
  • Then [edit] your question with a [mcve]. I just tried it with the example given here and it works just fine. – Martijn Pieters Nov 16 '17 at 11:40
  • (so `from collections import OrderedDict`, then `list_to_be_sorted = ...` where `...` is the first code block shown here, then `sorted(list_to_be_sorted, key=lambda k: k['id'])`, produces the desired output). – Martijn Pieters Nov 16 '17 at 11:41
  • See https://gist.github.com/mjpieters/ccde7384ab87e670180e064aff5edef3 – Martijn Pieters Nov 16 '17 at 11:42

0 Answers0