首页 > 解决方案 > 在插入时对 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

标签: pythonpython-3.xdictionaryordereddictionarylexicographic

解决方案


我有点困惑。听起来您指的是 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 可以保存数百万个值,但会立即查找值。


推荐阅读