【问题标题】:How can I write my own OrderedDict class in Python?如何在 Python 中编写自己的 OrderedDict 类?
【发布时间】:2016-05-16 17:05:24
【问题描述】:

基本上,我想了解这件事是如何运作的。我试图创建一个元组列表 [(), (), ...],每个元组都有两个值,qst 是键,第二个是值。但这不是真正的字典,也存在性能问题(我的意思是读/写/删除操作。

那么我应该如何编写一个 MyOrderedDict 类,它将(可能)扩展默认的 dict 类。

任何提示或资源将不胜感激。

PS:我们在 Django 中有类似的功能。 SortedDict

from django.utils.datastructures import SortedDict

它们在实施中是否相同或遵循相同的方法?

Help on class SortedDict in module django.utils.datastructures:

class SortedDict(__builtin__.dict)
 |  A dictionary that keeps its keys in the order in which they're inserted.
 |  
 |  Method resolution order:
 |      SortedDict
 |      __builtin__.dict
 |      __builtin__.object
 |  
 |  Methods defined here:

【问题讨论】:

  • the source
  • 查看源代码是个好主意,但彼得给出的链接是一个非常旧的 Python 版本。 new source is here。请注意,Python 3.6 将在 C 中实现它。
  • @CodyPiersall :我不认为 SortedDict 像你说的那样工作。我已更新问题详情,请参阅SortedDict 的文档字符串
  • 糟糕!你绝对是对的。我在想sorteddict on PyPI。我要删除我的超级错误评论。
  • 您可以在ActiveState查看更短的食谱

标签: python django python-2.7 dictionary ordereddictionary


【解决方案1】:

您可以查看source in Python 2。它似乎是用 C for Python 3 实现的。

【讨论】:

  • 这应该是一条评论
  • 为什么要评论?
【解决方案2】:

该类将管理字典和列表。在幕后,对于每个标准的 dict 操作,它将同时使用:

Dvalues = {"foo":"x","bar":"y","baz":"z"}
Lorder = ["bar","baz","foo"]

通过键获取值,作为标准字典:

return Dvalues[key]

按输入的 m 顺序获取值:

return Dvalues[Lorder[m]]

添加键、值:

Dvalues[key] = value
Lorder.append(key)

等等

【讨论】:

  • 这就是 SortedDict 在内部所做的。不利的一面是,随着条目数量的增加,删除条目会变慢(除非您总是删除最旧的条目),因为必须线性搜索列表。 SortedDict 对我来说用词不当,因为这意味着条目按排序顺序迭代。 OrderedDict 通过使用来自 Python 对象的双向链表避免了性能下降,这在另一端浪费了大量内存。也许这就是在 CPython 3.6 中用 C 重新实现它的原因。
猜你喜欢
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多