首页 > 解决方案 > 如何在忽略特定字符的同时对字典中的键进行排序?

问题描述

我有一本这样的字典:

>>> dictionary = {34: "martsz", 79: "David", "": "Kathy", 63: "Daniel"}

我想在不改变“”位置的情况下按键对其进行排序,所以它可以变成这样:

>>> dictionary
{34: "martsz", 63: "Daniel", "": "Kathy", 79: "David"}

标签: pythondictionary

解决方案


因为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


推荐阅读