PYTHON之Ordered Dict

来源:互联网 发布:网络课程 知乎 编辑:程序博客网 时间:2024/05/22 06:29
python有一个排序字典对象,但是很少有人提及
>>> d = OrderedDict([('a', 'b'), ('c', 'd')])>>> d.update({'foo': 'bar'})>>> dcollections.OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])

以下的基本操作as keys()values() and items() 还是支持的

>> d = OrderedDict([('a', 'b'), ('c', 'd')])>>> d.update({'foo': 'bar'})>>> dcollections.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/


0 0