I'm looking for a method to sort a list of dicts to obtain a 'natural sort order'. I have found the module natsort
, but apparantly I'm not using it right to get the list of dictionaries correctly sorted. Can anyone help to find my error?
Here's my code:
from operator import itemgetter
import natsort
# Example list an dict
list = ['13h', '1h', '3h']
dict = [{'a': '13h', 'b': 3}, {'a': '1h', 'b': 1}, {'a': '3h', 'b': 0}]
# Sort the list
natsort.natsorted(list, key=lambda y: y.lower())
# Sort the dict
# Later I also want to sort on several keys, therefore the itemgetter
sorted(dic, key=itemgetter(*['a']))
You can substitute natsort.natsorted
instead of sorted()
in your code and it should work. Example -
natsort.natsorted(dic, key=itemgetter(*['a']))
This should return a list of dictionaries, where the elements are sorted based on value of key 'a'
.