【问题标题】:Pythonic Way of Lexicographically Sorting Keys of an OrderedDict On Insert在插入时对 OrderedDict 的键进行字典排序的 Pythonic 方式
【发布时间】:2021-05-12 20:28:41
【问题描述】:

我有一个跟踪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

【问题讨论】:

  • 您的问题到底是什么?此外,与其发明自定义 API,不如将其设为 MutableMapping,这样您就可以真正将其用作字典替代品了?
  • 有序字典只记得插入顺序。您必须跟踪词汇顺序,例如在单独的列表中。因此,您可以创建一个按词汇顺序保存 ID 的列表。在每次插入时,您都会找到插入点(例如通过二叉树搜索)并在相应的列表位置添加 ID。

标签: python python-3.x dictionary ordereddictionary lexicographic


【解决方案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 可以保存数百万个值,但会立即查找值。

【讨论】:

  • 我认为,OP 指的是来自collectionsOrderedDict,但为SortedDict +1,不知道那个,现在我在 OP 下的评论听起来很愚蠢。
  • @Dschoni 我认为集合中的 OrderedDict 已集成到 python 的内置 dict() 中。也就是说,所有 dict() 都已经是 OrderedDicts。因此,不再需要来自集合的那个。
猜你喜欢
  • 2011-12-23
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 2015-10-08
相关资源
最近更新 更多