有序Dict类型(python)

前段时间写一个简单地dict类型数据传入一个函数并输出,发现它的输出顺序并不是按照我实际输入的顺序,我是学java出生的,于是想到它跟Map这种数据类型一样也是无序的(除了LinkedHashMap),让我们来看下提取的关键官方文档。

5.8. Mapping Types — dict

A mapping object maps hashable values to arbitrary objects.
A dictionary’s keys are almost arbitrary values.

学过数据结构的人都知道,程序执行和内存分配的关系,dict类型需要key计算出的hash值作为值对象的实际地址,而计算出hash值是随机的,所以说一个没经过特殊处理的dict类型肯定是没有可靠地顺序的,但是鄙人今天无心发现一个新的类型OrderedDict,不过这种类型不到必须使用的情况下最好不要使用,这种原理我估计跟java的LinkedHashMap类似,第一多占内存(维护顺序的链接关系),第二必定比dict加了些代码,就这两点就足以影响程序性能了。


以下是官网的描述和代码示例:

PEP 372: Adding an Ordered Dictionary to collections

The OrderedDict API provides the same interface as regular dictionaries but iterates over keys and values in a guaranteed order depending on when a key was first inserted:

>>> from collections import OrderedDict 
>>> d = OrderedDict([('first', 1), 
...                  ('second', 2), 
...                  ('third', 3)]) 
>>> d.items() [('first', 1), ('second', 2), ('third', 3)]
If a new entry overwrites an existing entry, the original insertion position is left unchanged:

>>> d['second'] = 4
>>> d.items()
[('first', 1), ('second', 4), ('third', 3)]



Deleting an entry and reinserting it will move it to the end:

>>> del d['second']
>>> d['second'] = 5
>>> d.items()
[('first', 1), ('third', 3), ('second', 5)]



The popitem() method has an optional last argument that defaults to True. If last is True, the most recently added key is returned and removed; if it’s False, the oldest key is selected:

>>> od = OrderedDict([(x,0) for x in range(20)])
>>> od.popitem()
(19, 0)
>>> od.popitem()
(18, 0)
>>> od.popitem(last=False)
(0, 0)
>>> od.popitem(last=False)
(1, 0)





Comparing two ordered dictionaries checks both the keys and values, and requires that the insertion order was the same:

>>> od1 = OrderedDict([('first', 1),
...                    ('second', 2),
...                    ('third', 3)])
>>> od2 = OrderedDict([('third', 3),
...                    ('first', 1),
...                    ('second', 2)])
>>> od1 == od2
False
>>> # Move 'third' key to the end
>>> del od2['third']; od2['third'] = 3
>>> od1 == od2
True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值