zoukankan      html  css  js  c++  java
  • What’s New in Python 2.7 — Python 3.4.0b2 documentation

    What’s New in Python 2.7 — Python 3.4.0b2 documentation

    PEP 372: Adding an Ordered Dictionary to collections

    Regular Python dictionaries iterate over key/value pairs in arbitrary order. Over the years, a number of authors have written alternative implementations that remember the order that the keys were originally inserted. Based on the experiences from those implementations, 2.7 introduces a new OrderedDict class in the collections module.

    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
  • 相关阅读:
    Spring(八)-spring5框架新功能
    Spring(七)-事务操作
    Spring(五)-AOP
    Linux errno错误码
    思考:如何保证服务稳定性?
    CPU性能分析工具原理
    Oracle数据库url格式
    java对象的四种引用:强引用、软引用、弱引用和虚引用
    给老板汇报技术规划的要点
    后端程序员必备:分布式事务基础篇
  • 原文地址:https://www.cnblogs.com/lexus/p/3529325.html
Copyright © 2011-2022 走看看