使用 natsort 对字典列表进行排序以获得自然排序顺序

Jok*_*oko 3 python sorting dictionary natsort

我正在寻找一种对字典列表进行排序以获得“自然排序顺序”的方法。我已经找到了该模块natsort,但显然我没有正确使用它来正确排序字典列表。任何人都可以帮助找到我的错误吗?

这是我的代码:

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']))
Run Code Online (Sandbox Code Playgroud)

Ana*_*mar 5

您可以在代码中替换而natsort.natsorted不是它应该可以工作。sorted()例子 -

natsort.natsorted(dic, key=itemgetter(*['a']))
Run Code Online (Sandbox Code Playgroud)

这应该返回一个字典列表,其中元素根据 key 的值排序'a'