python - 如何在忽略特定字符的同时对字典中的键进行排序?
问题描述
我有一本这样的字典:
>>> dictionary = {34: "martsz", 79: "David", "": "Kathy", 63: "Daniel"}
我想在不改变“”位置的情况下按键对其进行排序,所以它可以变成这样:
>>> dictionary
{34: "martsz", 63: "Daniel", "": "Kathy", 79: "David"}
解决方案
因为python3.6字典是插入顺序的,所以如果你有一个 python 版本> = 3.6,你可以使用:
dictionary = {34: "martsz", 79: "David", "": "Kathy", 63: "Daniel"}
i = next(i for i, e in enumerate(dictionary) if e == "")
idx = sorted(e for e in dictionary if e != "")
idx.insert(i, "")
dictionary = {e: dictionary[e] for e in idx}
dictionary
输出:
{34: 'martsz', 63: 'Daniel', '': 'Kathy', 79: 'David'}
对于其他 python 版本,您可以使用OrderedDict
推荐阅读
- android - 如何在 Android 的 camera2 中正确使用新的 createCaptureSession()?
- elasticsearch - Elasticsearch 中复合查询中的自定义评分函数
- .net - 在 WinForms 上打开 RDLC 时如何解决问题?
- c# - 给定的程序集名称或代码库“System.Data.SqlServerCe”无效。不知道为什么
- java - 在底部导航视图中添加 Textview
- r - 如何在ggplot中基于Y轴分配色标
- python - 使用 PIL 和 Imageio 正确加载二进制掩码/GIF
- javascript - 如何在js中使用EAN13验证条形码
- hibernate - Spring JPA Hibernate 阻止在控制台日志中显示 sql
- azure - 如果使用 azure datafactory 存在准备好的文件,如何加载 csv 文件