python 字典排列顺序的字典有顺序的吗

Python 字典的比较方法
  在Python 中 字典的比较顺序如下所示:
  字典的长度比较===&字典的键值比较(严格按照hasKeys()的顺序)===&各键值对应的值Python的字典排序_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
Python的字典排序
上传于|0|0|暂无简介
阅读已结束,如果下载本文需要使用5下载券
想免费下载本文?
定制HR最喜欢的简历
你可能喜欢1694人阅读
Python(13)
在使用Python的字典时,我们发现,当输出字典的内容时,输出内容的顺序和我们建立字典时候添加内容的输入顺序不一致。其
实,我们使用的是Python默认的字典,这种字典是不按顺序存储、输出我们添加在字典中的内容的。要想输出内容的顺序和我们建
立字典时候添加内容的输入顺序一致,就要用到有序字典。
defaultdict
使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict:
&&& from collections import defaultdict
&&& dd = defaultdict(lambda: 'N/A')
&&& dd['key1'] = 'abc'
&&& dd['key1']
&&& dd['key2']
注意默认值是调用函数返回的,而函数在创建defaultdict对象时传入。
除了在Key不存在时返回默认值,defaultdict的其他行为跟dict是完全一样的。
OrderedDict
使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。
如果要保持Key的顺序,可以用OrderedDict:
&&& from collections import OrderedDict
&&& d = dict([('a', 1), ('b', 2), ('c', 3)])
{'a': 1, 'c': 3, 'b': 2}
&&& od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:
&&& od = OrderedDict()
&&& od['z'] = 1
&&& od['y'] = 2
&&& od['x'] = 3
&&& od.keys()
['z', 'y', 'x']
OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key:
from collections import OrderedDict
class LastUpdatedOrderedDict(OrderedDict):
def __init__(self, capacity):
super(LastUpdatedOrderedDict, self).__init__()
self._capacity = capacity
def __setitem__(self, key, value):
containsKey = 1 if key in self else 0
if len(self) - containsKey &= self._capacity:
last = self.popitem(last=False)
print 'remove:', last
if containsKey:
del self[key]
print 'set:', (key, value)
print 'add:', (key, value)
OrderedDict.__setitem__(self, key, value)
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
class&collections.OrderedDict([items])
Return an instance of a dict subclass, supporting the usual&&methods.
An&OrderedDict&is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
New in version 3.1.
popitem(last=True)
The&&method
for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if&last&is true or FIFO order if false.
move_to_end(key,&last=True)
Move an existing&key&to either end of an ordered dictionary. The item is moved to the right end if&last&is true (the default) or to the beginning if&last&is false. Raises&&if
the&key&does not exist:
&&& d = OrderedDict.fromkeys('abcde')
&&& d.move_to_end('b')
&&& ''.join(d.keys())
&&& d.move_to_end('b', last=False)
&&& ''.join(d.keys())
New in version 3.2.
In addition to the usual mapping methods, ordered dictionaries also support reverse iteration using&.
Equality tests between&&objects
are order-sensitive and are implemented as&list(od1.items())==list(od2.items()).
Equality tests between&&objects
and other&&objects
are order-insensitive like regular dictionaries. This allows&&objects
to be substituted anywhere a regular dictionary is used.
The&&constructor
and&update()&method both accept keyword arguments, but their order is
lost because Python’s function call semantics pass in keyword arguments using a regular unordered dictionary.
8.3.6.1.&&Examples
and Recipes
Since an ordered dictionary remembers its insertion order, it can be used in conjunction with sorting to make a sorted dictionary:
&&& # regular unsorted dictionary
&&& d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
&&& # dictionary sorted by key
&&& OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
&&& # dictionary sorted by value
&&& OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
&&& # dictionary sorted by length of the key string
&&& OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.
It is also straight-forward to create an ordered dictionary variant that remembers the order the keys were&last&inserted. If a new entry overwrites an existing entry, the original insertion position
is changed and moved to the end:
class LastUpdatedOrderedDict(OrderedDict):
'Store items in the order the keys were last added'
def __setitem__(self, key, value):
if key in self:
del self[key]
OrderedDict.__setitem__(self, key, value)
An ordered dictionary can be combined with the&&class
so that the counter remembers the order elements are first encountered:
class OrderedCounter(Counter, OrderedDict):
'Counter that remembers the order elements are first encountered'
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
def __reduce__(self):
return self.__class__, (OrderedDict(self),)
有序字典OrderedDict是Python的内建模块collections的一个函数,使用时可以用“from & collections & import & &OrderedDict”导入使用
& & & & & & & &
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:22008次
排名:千里之外
原创:11篇
转载:88篇
(14)(27)(5)(15)(1)(9)(10)(2)(1)(3)(2)(7)(4)

我要回帖

更多关于 python 有顺序的字典 的文章

 

随机推荐