I need to sort a list of dictionaries by a specific value. Unfortunately, some values are None and the sorting does not work in Python 3 because of the fact that it does not support comparison of None with not None values. I need to retain the None values as well and place them as lowest values in the new sorted list.
The code:
import operator
list_of_dicts_with_nones = [
{"value": 1, "other_value": 4},
{"value": 2, "other_value": 3},
{"value": 3, "other_value": 2},
{"value": 4, "other_value": 1},
{"value": None, "other_value": 42},
{"value": None, "other_value": 9001}
]
# sort by first value but put the None values at the end
new_sorted_list = sorted(
(some_dict for some_dict in list_of_dicts_with_nones),
key=operator.itemgetter("value"), reverse=True
)
print(new_sorted_list)
What I get in Python 3.6.1:
Traceback (most recent call last):
File "/home/bilan/PycharmProjects/py3_tests/py_3_sorting.py", line 15, in <module>
key=operator.itemgetter("value"), reverse=True
TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
What I need (this works in Python 2.7):
[{'value': 4, 'other_value': 1}, {'value': 3, 'other_value': 2}, {'value': 2, 'other_value': 3}, {'value': 1, 'other_value': 4}, {'value': None, 'other_value': 42}, {'value': None, 'other_value': 10001}]
Yes, I know there are similar questions to this one, but they do not deal with this particular use case with operator.itemgetter:
A number smaller than negative infinity in python?
Is everything greater than None?
Comparing None with built-in types using arithmetic operators?
I can recreate the sorting behavior of Python 2 in Python 3 when there are no dictionaries involved. But I don't see a way to do this with the operator.