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

标签 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']))

最佳答案

您可以在代码中用 natsort.natsorted 代替 sorted(),它应该可以工作。示例 -

natsort.natsorted(dic, key=itemgetter(*['a']))

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

关于python - 使用 natsort 对字典列表进行排序以获得自然排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33278514/

相关文章:

python - 如何使用脚本重新创建 IPython 的 '--pylab' 选项的效果?

PHP MySQL 菜单排序

python - 带有 URL 的 pip -U -r requirements.txt 不断重新安装

python - 当我提到它时,让机器人用前缀进行响应

python - Tkinter 文本框索引删除 1.10 不起作用

c++ - 按 STL - C++ 中的成绩对学生列表进行排序?

sorting - 使用 std::collections::BinaryHeap 就地堆排序

java - 从多个 Enum 类型为 Map 创建唯一键

c++ - 无法迭代 Poco::Any 的 std::map

android - 在离线静态图像 (jpeg) 上显示用户的当前位置 - Android