python - 嵌套 Python 字典排序
问题描述
我有一个具有以下格式的 python 字典。
{'range_qty':
{'0 to 10 qty': 5,
'more than 5000 qty': 18,
'500 to 1000 qty': 20,
'200 to 500 qty': 19,
'1000 to 5000 qty': 15,
'10 to 50 qty': 3,
'50 to 200 qty': 14}}
如何按键对这本字典进行排序?我需要像这样的输出
{'range_qty':
{'0 to 10 qty': 5,
'10 to 50 qty': 3,
'50 to 200 qty': 14,
'200 to 500 qty': 19,
'500 to 1000 qty': 20,
'1000 to 5000 qty': 15,
'more than 5000 qty': 18,
}}
解决方案
使用自定义排序。
前任:
import sys
def cust_sort(val):
i = val[0].split(" ", 1)[0]
if not i.isdigit():
return sys.maxsize
return int(i)
data = {'range_qty':
{'0 to 10 qty': 5,
'more than 5000 qty': 18,
'500 to 1000 qty': 20,
'200 to 500 qty': 19,
'1000 to 5000 qty': 15,
'10 to 50 qty': 3,
'50 to 200 qty': 14}}
data = sorted(data['range_qty'].items(), key=cust_sort)
#or data = {'range_qty': dict(sorted(data['range_qty'].items(), key=cust_sort))}
print(data)
输出:
[('0 to 10 qty', 5),
('10 to 50 qty', 3),
('50 to 200 qty', 14),
('200 to 500 qty', 19),
('500 to 1000 qty', 20),
('1000 to 5000 qty', 15),
('more than 5000 qty', 18)]
推荐阅读
- matlab - 如何获得矩阵的特定大小
- node.js - 后端 API 获取,而不是 React
- linux - 相比之下,为什么 docker 入口点脚本在容器内手动完美运行时会失败?
- python-3.x - 获取回文数列表的哪个代码更可取?
- python - 录制视频,自动保存,然后重新录制
- python - 如何在python中处理像�这样的特殊字符?
- python - 如何强制键盘焦点在特定的小部件/QGroupBox(PyQt5)上?
- c++ - Cmake - 我必须运行 cmake --build 。构建二进制文件两次
- docker - 为什么 Docker 在更改使用 --chmod 标志复制的文件的权限后会使构建缓存无效?
- azure - 带有 Terraform 的 Azure Policy 自定义模板