2
votes

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']))
1
Have you tried - natsort.natsorted(dic, key=itemgetter(*['a'])) ? - Anand S Kumar
No. Lol, it works. That means I already had the answer :/ - Joko
Is there a reason you are using key=lambda y: y.lower() on the first pass? It looks like your data is already lowercase. - SethMMorton

1 Answers

3
votes

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' .