【问题标题】:How to create a sorted dictionary in Python by key (alphabetically)如何在 Python 中按键创建排序字典(按字母顺序)
【发布时间】:2022-01-23 17:04:09
【问题描述】:

从 Python 3.7 开始,字典是“有序的”,其中迭代基于“插入顺序”。

我想要一个 Python 中的字典,其中迭代基于键的字母顺序,即字典按键的字母顺序排序。

即如下字典:

dictionary = {}
dictionary["b"] = 1
dictionary["a"] = 2

将产生以下输出:

for key in dictionary:
    print(key) # a, b

是否有一些用于“排序字典”的内置 Python 类,类似于我们为插入顺序使用 OrderedDict 的方式?

注意:我不认为这是任何现有问题的重复,这些问题似乎只提到:

  • 有序字典(按插入顺序排序的字典)- 这不是我要找的。​​li>
  • 按值排序的字典 -- 我正在寻找按键排序的字典。
  • 事后对字典进行排序,而不是在添加/删除元素时自动(且高效地)排序。

我进行了多次 Google 搜索,但找不到答案。

【问题讨论】:

  • 我非常怀疑是否会有一个按字母顺序排序的字典的内置类,因为它会受到仅限于字符串作为键的限制。
  • @SujalSingh 我想会有一些用于排序字典的类,它可能采用 lambda 排序函数或类似的东西。这样它不一定只适用于字符串。
  • google SortedDict python 应该是最佳结果
  • 非内置 - 最接近的是 SortedDict 模块:grantjenks.com/docs/sortedcontainers
  • @KellyBundy,我认为事后处理比在每次插入时重复重新排序元素更有效。也许我错过了什么......

标签: python sorting dictionary


【解决方案1】:

实际上有一个解决方案,来自 Mark Summerfield:使用 Python 进行快速 GUI 编程,我会谦虚地将它转移到这里。对马克的所有尊重:)

import bisect

class CustomOrderedDict(object):
    def __init__(self, dictionary=None):
        self.__keys = {}
        self.__dict = []
        if dictionary is not None:
            if isinstance(dictionary, CustomOrderedDict):
                self.__dict = dictionary.__dict.copy()
                self.__keys = dictionary.__keys[:]
            else:
                self.__dict = dict(dictionary).copy()
                self.__keys = sorted(self.__dict.keys())

    def getAt(self, index):
        return self.__dict[self.__keys[index]]

    def setAt(self, index, value):
        self.__dict[self.__keys[index]] = value
        return self.__dict[self.__keys[index]]

    def __getitem__(self, key):
        return self.__dict[key]

    def __setitem__(self, key, value):
        if key not in self.__dict:
            bisect.insort_left(self.__keys, key)
        self.__dict[key] = value

    def __delitem__(self, key):
        i = bisect.bisect_left(self.__keys, key)
        del self.__keys[i]
        del self.__dict[key]

    def setdefault(self, key, value):
        if key not in self.__dict:
            bisect.insort_left(self.__keys, key)
        return self.__dict.setdefault(key, value)

    def pop(self, key, value=None):
        if key not in self.__dict:
            return value
        i = bisect.bisect_left(self.__keys, key)
        del self.__keys[i]
        return self.__dict.pop(key, value)

    def popitem(self):
        item = self.__dict.popitem()
        i = bisect.bisect_left(self.__keys, item[0])
        del self.keys[i]
        return item

    def has_key(self, key):
        return key in self.__dict

    def __contains__(self, key):
        return key in self.__dict

    def __len__(self):
        return len(self.__dict)

    def keys(self):
        return self.__keys[:]

    def values(self):
        return [self.__dict[key] for key in self.__keys]

    def __iter__(self):
        return iter(self.__keys)

    def iterkeys(self):
        return iter(self.__keys)

    def itervalues(self):
        for key in self.__keys:
            yield self._dict[key]

    def iteritems(self):
        for key in self.__keys:
            yield key, self.__dict[key]

    def copy(self):  # shallow copy
        dictionary = CustomOrderedDict()
        dictionary.__keys = self.__keys[:]
        dictionary.__dict = self.__dict.copy()
        return dictionary

    def clear(self):
        self.__keys = []
        self.__dict = {}

    def __repr__(self):
        pieces = []
        for key in self.__keys:
            pieces.append("%r: %r" % (key, self.__dict[key]))  
        return "CustomOrderedDict({%s})" % ", ".join(pieces)


t = CustomOrderedDict(dict(s=1, a = 2, b =100, c = 200))


print t

结果:

CustomOrderedDict({'a': 2, 'b': 100, 'c': 200, 's': 1})

【讨论】:

  • 这是一个非常先进的解决方案,但我认为它非常优雅,并且具有普通字典的所有功能。
  • 嗯,来自“非常先进”的解决方案,我希望比线性时间插入/删除更好。
  • 我肯定愿意接受提案 :)
  • 我看到你删除了让我发笑的有趣代码 cmets。伤心。
猜你喜欢
  • 1970-01-01
  • 2023-02-09
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 2020-01-22
相关资源
最近更新 更多