对于一个能够保存键值插入顺序的字典,是如何实现的?

主要有两点:

  一个双向链表,用来记录字典的键值的插入顺序

  一个键和链表节点的映射,主要用来删除键的时候,找到键对应的节点

python代码实现

class Link:
__slots__ = 'prev', 'next', 'key' class OrderDict:
def __init__(self):
self.root = Link()
self.map = {}
self._node_map = {}
self.root.next = self.root
self.root.prev = self.root def __setitem__(self, key, value):
if key in self._node_map:
self.map[key] = value
else:
root = self.root
last = root.prev
link = Link()
link.prev, link.next, link.key = last, root, key
last.next = link
root.prev = link
self._node_map[key] = link
self.map[key] = value def __getitem__(self, item):
return self.map[item] def __delitem__(self, key):
del self.map[key]
link = self._node_map.pop(key)
link_prev, link_next = link.prev, link.next
link_prev.next, link_next.prev = link_next, link_prev
link.prev, link.next = None, None def pop(self):
"""
LIFO
:return:
"""
if not self._node_map:
raise KeyError('dict is empty')
root = self.root
link = root.prev
link_prev = link.prev
link_prev.next = root
root.prev = link_prev
link.prev, link.next = None, None
self._node_map.pop(link.key)
return self.map.pop(link.key) def __iter__(self):
root = self.root
curr = root.next
while curr != root:
yield curr.key
curr = curr.next def values(self):
root = self.root
curr = root.next
while curr != root:
yield self.map[curr.key]
curr = curr.next
    def __str__(self):
root = self.root
curr = root.next
out = []
while curr != root:
out.append((curr.key, self.map[curr.key]))
curr = curr.next
return str(out) if __name__ == '__main__':
d = OrderDict()
d['a'] = '1'
d['b'] = '2'
d['c'] = 'c'
print(d)

python实现有序字典的更多相关文章

  1. python 实现有序字典

    python 实现有序字典 Python默认的字典,是不按顺序存储.输出我们添加在字典中的内容的,即是无序的字典.python 使用OrderedDict函数实现有序的字典. 示例: d = dict ...

  2. python创建有序字典及字典按照值的大小进行排序

    有序字典 在Python中,字典类型里面的元素默认是无序的,但是我们也可以通过collections模块创建有序字典 # -*- coding:utf-8 -*- # python有序字典需导入模块c ...

  3. python创建有序字典OrderedDict()

    python 有序字典OrderedDict # -*- coding:utf-8 -*- """ python有序字典 需导入模块collections "& ...

  4. python 学习 有序字典

    自定义创建有序字典类 dict的__getitem__方法 有些不同,想使用自定义__getitem__方法显示查询key的下标:需要研究 #/usr/bin/env python3 # -*- co ...

  5. python有序字典OrderedDict()

    转python创建有序字典OrderedDict # -*- coding:utf-8 -*- """ python有序字典 需导入模块collections " ...

  6. python基础知识4——collection类——计数器,有序字典,默认字典,可命名元组,双向队列

    1.计数器(counter) Counter是对字典类型的补充,用于追踪值的出现次数. ps:具备字典的所有功能 + 自己的功能  Counter 我们从中挑选一些相对常用的方法来举例: 在上面的例子 ...

  7. python模块介绍- collections(5)-OrderedDict 有序字典

    1.3.5 OrderedDict 有序字典 OrderedDict是dict的子类,它记住了内容添加的顺序. import collections print 'Regular dictionary ...

  8. Python学习笔记——基础篇2【第三周】——计数器、有序字典、元组、单(双)向队列、深浅拷贝、函数、装饰器

    目录 1.Python计数器Counter 2.Python有序字典OrderredDict 3.Python默认字典default 4.python可命名元组namedtuple 5.Python双 ...

  9. python之单例模式、栈、队列和有序字典

    一.单例模式 import time import threading class Singleton(object): lock = threading.RLock() # 定义一把锁 __inst ...

随机推荐

  1. [Swift]LeetCode434. 字符串中的单词数 | Number of Segments in a String

    Count the number of segments in a string, where a segment is defined to be a contiguous sequence of ...

  2. [Swift]LeetCode960. 删列造序 III | Delete Columns to Make Sorted III

    We are given an array A of N lowercase letter strings, all of the same length. Now, we may choose an ...

  3. Vue实现移动端页面切换效果

    找了好多博客实现效果都……emmm…… 应用Vue自带的过渡 < 进入/离开 & 列表过渡 >和 嵌套路由 和 fixed定位实现 其实还是挺简单的. 在子页面把整个页面做绝对定位 ...

  4. BBS论坛(十一)

    11.1.前台用户模型创建 (1)apps/front/models.py 首先安装:pip install shortuuid class FrontUser(db.Model): __tablen ...

  5. UE4 打包C++项目到win32平台报错 could not find mspdbcore.dll

    解决方法: 将Visual Studio中相应系统(如32位对应x86.64位对应x64)下的 ms.*.dll 等一系列文件拷贝到 C:\Windows\System32\ 路径下.踩坑:不能只拷贝 ...

  6. 《HelloGitHub月刊》第 09 期

    <HelloGitHub>第 09 期 兴趣是最好的老师,<HelloGitHub>就是帮你找到兴趣! 前言 转眼就到年底了,月刊做到了第09期,感谢大家一路的支持和帮助

  7. Chapter 5 Blood Type——31

    I stood carefully, and I was still fine. He held the door for me, his smile polite but his eyes mock ...

  8. [开发技巧]·TensorFlow中numpy与tensor数据相互转化

    [开发技巧]·TensorFlow中numpy与tensor数据相互转化 个人主页–> https://xiaosongshine.github.io/ - 问题描述 在我们使用TensorFl ...

  9. Linux驱动模块编译模板

    hello.c文件: #include <linux/module.h> #include <linux/kernel.h> static int hello_init(voi ...

  10. XSS DOM 测试

    dvwa DOM XSS DOM Based XSS:是基于DOM文档对象模型的操作,通过前端脚本修改页面的DOM节点形成的XSS,该操作不与服务器端进行交互,而且代码是可见的,从前端获取到DOM中的 ...