Python collections系列之有序字典
有序字典(orderedDict )
orderdDict是对字典类型的补充,他记住了字典元素添加的顺序
1、创建一个有序字典
import collections dic = collections.OrderedDict()
dic['k1'] = 'v1'
dic['k2'] = 'v2'
dic['k3'] = 'v3'
2、查看有序字典
print(dic) 输出结果:
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
3、对比有序字典和字典
import collections dic1 = collections.OrderedDict() # 有序字典
dic1['k1'] = 'v1'
dic1['k2'] = 'v2'
dic1['k3'] = 'v3' dic2 = dict() # 字典
dic2['k1'] = 'v1'
dic2['k2'] = 'v2'
dic2['k3'] = 'v3' print(dic) 输出结果
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]) # 有序的
{'k2': 'v2', 'k1': 'v1', 'k3': 'v3'} #无序的
4、查看有序字典的方法
>>> dir(dic)
['_OrderedDict__hardroot', '_OrderedDict__map', '_OrderedDict__marker', '_OrderedDict__root', '_OrderedDict__update', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'move_to_end', 'pop', 'popitem', 'setdefault', 'update', 'values']
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries. # The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY]. def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary. '''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
return dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, _ = self.__map.pop(key)
link_prev[1] = link_next # update link_prev[NEXT]
link_next[0] = link_prev # update link_next[PREV] def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
root = self.__root
curr = root[1] # start at the first node
while curr is not root:
yield curr[2] # yield the curr[KEY]
curr = curr[1] # move to next node def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
root = self.__root
curr = root[0] # start at the last node
while curr is not root:
yield curr[2] # yield the curr[KEY]
curr = curr[0] # move to previous node def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
dict.clear(self) # -- the following methods do not depend on the internal structure -- def keys(self):
'od.keys() -> list of keys in od'
return list(self) def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self] def items(self):
'od.items() -> list of (key, value) pairs in od'
return [(key, self[key]) for key in self] def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self) def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k] def iteritems(self):
'od.iteritems -> an iterator over the (key, value) pairs in od'
for k in self:
yield (k, self[k]) update = MutableMapping.update __update = update # let subclasses override update without breaking __init__ __marker = object() def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised. '''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false. '''
if not self:
raise KeyError('dictionary is empty')
key = next(reversed(self) if last else iter(self))
value = self.pop(key)
return key, value def __repr__(self, _repr_running={}):
'od.__repr__() <==> repr(od)'
call_key = id(self), _get_ident()
if call_key in _repr_running:
return '...'
_repr_running[call_key] = 1
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
finally:
del _repr_running[call_key] def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,) def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self) @classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None. '''
self = cls()
for key in iterable:
self[key] = value
return self def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive. '''
if isinstance(other, OrderedDict):
return dict.__eq__(self, other) and all(_imap(_eq, self, other))
return dict.__eq__(self, other) def __ne__(self, other):
'od.__ne__(y) <==> od!=y'
return not self == other # -- the following methods support python 3.x style dictionary views -- def viewkeys(self):
"od.viewkeys() -> a set-like object providing a view on od's keys"
return KeysView(self) def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self) def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)
OrderedDict
5、有序字典的常用操作方法
# setdefault 设置新键的值,默认为None import collections dic = collections.OrderedDict()
dic['k1'] = 'v1'
dic['k2'] = 'v2'
dic['k3'] = 'v3' dic['k4'] = None
dic.setdefault('k5')
dic.setdefault('k6', 'v6') print(dic)
输出结果:
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', None), ('k5', None), ('k6', 'v6')])
# move_to_end 移动某个key到最后 import collections dic = collections.OrderedDict()
dic['k1'] = 'v1'
dic['k2'] = 'v2'
dic['k3'] = 'v3' print(dic) dic.move_to_end('k1') print(dic) 输出结果:
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')])
# pop 删除某个key import collections dic = collections.OrderedDict()
dic['k1'] = 'v1'
dic['k2'] = 'v2'
dic['k3'] = 'v3' print(dic) dic.pop('k2')
ret = dic.pop('k2') print(dic)
print(ret) 输出结果:
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
OrderedDict([('k1', 'v1'), ('k3', 'v3')])
v2
# update 新增某个key或刷新某个key值 import collections dic = collections.OrderedDict()
dic['k1'] = 'v1'
dic['k2'] = 'v2'
dic['k3'] = 'v3' print(dic) dic.update({'k1':'v111','k10':'v10'}) print(dic) 输出结果:
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
OrderedDict([('k1', 'v111'), ('k2', 'v2'), ('k3', 'v3'), ('k10', 'v10')])
Python collections系列之有序字典的更多相关文章
- Python collections系列之默认字典
默认字典(defaultdict) defaultdict是对字典的类型的补充,它默认给字典的值设置了一个类型. 1.创建默认字典 import collections dic = collecti ...
- python模块介绍- collections(5)-OrderedDict 有序字典
1.3.5 OrderedDict 有序字典 OrderedDict是dict的子类,它记住了内容添加的顺序. import collections print 'Regular dictionary ...
- 【python】collections模块(有序字典,计数器,双向队列)
collections模块基本介绍 我们都知道,Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上 ...
- python(3)-计数器,有序字典
计数器:Counter 在使用计数器之前需要先 import collections >>> import collections >>> obj = collec ...
- Python collections系列之计数器
计数器(counter) Counter是对字典(无序)类型的补充,用于追踪值的出现次数. 使用counter需要导入 collections 类 ps:具备字典的所有功能 + 自己的功能 1.创建一 ...
- Python collections系列之单向队列
单向队列(deque) 单项队列(先进先出 FIFO ) 1.创建单向队列 import queue q = queue.Queue() q.put(') q.put('evescn') 2.查看单向 ...
- Python collections系列之双向队列
双向队列(deque) 一个线程安全的双向队列 1.创建一个双向队列 import collections d = collections.deque() d.append(') d.appendle ...
- Python collections系列之可命名元组
可命名元组(namedtuple) 根据nametuple可以创建一个包含tuple所有功能以及其他功能的类 1.创建一个坐标类 import collections # 创建类, defaultd ...
- python递归、collections系列以及文件操作进阶
global log 127.0.0.1 local2 daemon maxconn log 127.0.0.1 local2 info defaults log global mode http t ...
随机推荐
- 【HackerRank】The Love-Letter Mystery
James找到了他的朋友Harry要给女朋友的情书.James很爱恶作剧,所以他决定要胡搞一下.他把信中的每个单字都变成了回文.对任何给定的字符串,他可以减少其中任何一个字符的值,例如'd'可以变成' ...
- 试坑不完美的 clip-path (我说的 CSS 的那个)
需求跟我说,咱们要创新,想做一个蜂巢状的列表,年少无知的我竟然一口答应了,全然因为刚接触了 clip-path: But,然而,不幸的是,这只是坎坷路途的开始.... clip-path 的教程很多了 ...
- console、JSON兼容问题
console在ie8上面竟然有兼容问题,JSON.stringify()在ie10下竟然会报错,再页面上引用一个json2.js能解决此问题.
- Android系统开发--灯光系统之电池灯的流程分析
Android系统开发--Android灯光系统之电池灯的流程分析 前期系统准备 运行初始化,创建系统服务 创建电池服务,获得电池灯;创建监听者监听上报电池事件: mSystemServiceMana ...
- Linux之Xinetd服务介绍
一.概念:1.独立启动的守护进程:stand-alone,每个特定服务都有单独的守护进程,这个处理单一服务的始终存在的进程就是独立启动的守护进程. 2.超级守护进程:多个服务统一由一个进程管理,该进程 ...
- 如何用Qt写一个同一时间只能运行一个实例的应用程序
http://blog.sina.com.cn/s/blog_6343941a0100nk2x.html 可以达到的目的: 1.应用只启动一个实例,依赖于QtNetwork模块 2.启动时向另一个实例 ...
- 爬虫之MongoDB的图片
聚合:
- jedis的源码理解-基础篇
[jedis的源码理解-基础篇][http://my.oschina.net/u/944165/blog/127998] (关注实现关键功能的类) 基于jedis 2.2.0-SNAPSHOT ...
- 用createinstallmedia创建可恢复的OSX安装DMG
准备 从App Store下载OS X安装程序,下载完成,会在应用程序目录 /Applications 下找到类似 Install OS X 10.xxxxxx.app(中文名如:安装 OS X 10 ...
- spring mvc中,如何在 Java 代码里,获取 国际化 内容
首先,在Spring的application.xml中定义 <bean id="messageSource" class="org.springframework. ...