python的collection系列-有序字典(OrderedDict)
2016-04-22 17:59
906 查看
orderdDict是对字典类型的补充,他记住了字典元素添加的顺序
注意:字典默认循环只输出key
注意:字典默认循环只输出key
import collections dic = collections.OrderedDict() dic["k1"] = "v1" dic["k2"] = "v2" dic["k3"] = "v3" print(dic) #实现原理:相当于用列表(有序)来维护字典(无序)排序,以下仅供理解 # dic = {"k1":"v1","k2":"v2"} # li = ["k1","k2"] # for i in li: # print(dic.get(i)) 执行结果:无论执行多少次结果一样 OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
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.
#有序删除和指定删除 import collections dic = collections.OrderedDict() dic["k1"] = "v1" dic["k2"] = "v2" dic["k3"] = "v3" print(dic) dic.popitem() #有序拿掉,每次拿掉最后一个,相当于内存的栈存放,后进先出原则,而pop()就是强制拿出指定的值 print(dic) 执行结果: OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]) OrderedDict([('k1', 'v1'), ('k2', 'v2')])
def move_to_end(self, key, last=True): '''Move an existing element to the end (or beginning if last==False). Raises KeyError if the element does not exist. When last=True, acts like a fast version of self[key]=self.pop(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')])
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
#添加默认键 import collections dic = collections.OrderedDict() dic["k1"] = "v1" dic["k2"] = "v2" dic["k3"] = "v3" print(dic) dic.setdefault("k4","v4") #默认键值为None,不过可以添加值 print(dic) #执行结果: OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]) OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')])
相关文章推荐
- 利用python实现对鼠标的移动点击操作
- 用Python登陆武汉理工大学无线校园网
- python解释器内建函数002
- Python3.5入门学习记录-File
- python unicode-escape编码问题
- python小技巧-基于python本身
- Python爬虫入门笔记:urllib库的使用
- Python中pip版本升级error:You are using pip version 7.1.2, however version 8.1.1 is available.
- python的collection系列-counter
- Python IDLE reload(sys)后无法正常执行命令的原因
- Python笔记01:sort min/max map/filter/reduce 列表解析 详解
- python基础
- Eclipse和PyDev搭建完美Python开发环境(Windows篇)
- python #coding:utf-8和setdefaultencoding有什么区别?
- Python处理Excel(一):Excel的简单处理
- LeetCode[Math]----Excel Sheet Column Title----Excel Sheet Column Number
- django/python日志logging 的配置以及处理
- 朴素贝叶斯算法Python实现
- windows下Python图形化工具Matplotlib安装
- python中的setdefaultencoding函数使用