python有一个排序字典对象,但是很少有人提及
>>> d = OrderedDict([('a', 'b'), ('c', 'd')])
>>> d.update({'foo': 'bar'})
>>> d
collections.OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])
以下的基本操作as keys(), values() and items() 还是支持的
>> d = OrderedDict([('a', 'b'), ('c', 'd')])
>>> d.update({'foo': 'bar'})
>>> d
collections.OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])
>>> d['spam'] = 'eggs'
>>> d.keys()
['a', 'c', 'foo', 'spam']
>>> d.values()
['b', 'd', 'bar', 'eggs']
>>> d.items()
[('a', 'b'), ('c', 'd'), ('foo', 'bar'), ('spam', 'eggs')]
但是OrderedDict.__reversed__()方法不支持了,提供了对KEY的reverse操作。以下是对json的使用
>>> items = [('one', 1), ('two', 2), ('three',3), ('four',4), ('five',5)]
>>> json.dumps(OrderedDict(items))
'{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}'
更多细节,请点这里http://legacy.python.org/dev/peps/pep-0372/
本文介绍了Python中有序字典的基本用法,包括初始化、更新及常用方法如keys()、values()和items()等,并展示了如何利用有序字典保持字典元素的插入顺序不变,最后通过JSON序列化的例子说明其应用。
3万+

被折叠的 条评论
为什么被折叠?



