在插入时按字典顺序对 OrderedDict 的键进行排序的 Pythonic 方式

问题描述

我有以下跟踪 OrderedDict 的类:

class LexDict:
    def __init__(self):
        self.m_map = OrderedDict() # maps string which is case-sensitive to int

    def set(self,id,seqNo):
        self.m_map[id] = seqNo

    def get(self,id): # seqNo returned
        return self.m_map[id] if self.has(id) else 0

    def has(self,id): # bool value
        return ( id in self.m_map.keys() )

    def to_str(self):
        stream = ""
        for key,value in self.m_map.items():
            stream = stream + key + ":" + str(value) + " "
        return stream.rstrip()

我的目标是更改 set() 方法以使其始终按字典顺序排列,以便无论何时调用 to_str() 都将按字典顺序排列。我们可以放心地假设该字典中的任何映射都不会被删除。这将用于网络情况,因此效率是关键,对整个列表进行排序而不是将其移动到正确的位置会影响性能。

如何使用它的示例。

a = LexDict()

a.set("/Justin",1) # the id will have "/"s (maybe even many) in it,we can image them without "/"s for sorting

a.set("/James",600)

a.set("/Austin",-123)
print( a.to_str() )

输出/Austin:-123 /James:600 /Justin:1

解决方法

我有点困惑。听起来您指的是 sortedcollections 模块中的 OrderedDict 类;该模块还包含您要查找的内容,即 SortedDict。通常,sortedcollections 模块包含许多容器,可以有效地使用大型列表和字典。例如,在 SortedDict 中查找时间是 O(log(n)) 而不是普通 python dict() 的 O(n)。

from sortedcollections import SortedDict

D = SortedDict([("/James",600),("/Justin",1),("/Austin",-123)])
print(D)

一般来说,SortedDict 和 SortedList 可以容纳数百万个值,但可以立即查找值。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...