I need help to sort my list of dicts.
my_list = [{'id': 1, 'code': '2'}, {'id': 2, 'code': 'b'}, {'id': 3, 'code': '1'}, {'id': 4, 'code': '10'}, {'id': 5, 'code': 'a'}]
import operator
my_list.sort(key=operator.itemgetter('code'))
Result:
[{'id': 3, 'code': '1'}, {'id': 4, 'code': '10'}, {'id': 1, 'code': '2'}, {'id': 5, 'code': 'a'}, {'id': 2, 'code': 'b'}]
I want to sort the list like that:
[{'id': 3, 'code': '1'}, {'id': 1, 'code': '2'}, {'id': 4, 'code': '10'}, {'id': 5, 'code': 'a'}, {'id': 2, 'code': 'b'}]
I didn't see answer to sort it.
You need to cast the numerical strings to int
(or float
) for the sorting not to be lexicographic on the numerical strings. A simple way is defining a custom sorting function as:
def custom_sort(x):
try:
return 0, float(x)
except ValueError:
return 1, x
my_list.sort(key= lambda x: custom_sort(x['code']))
print(my_list)
[{'id': 3, 'code': '1'},
{'id': 1, 'code': '2'},
{'id': 4, 'code': '10'},
{'id': 5, 'code': 'a'},
{'id': 2, 'code': 'b'}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.