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
  • 相关阅读:
    MySQL-keepalived做高可用
    Linux-服务管理
    MySQL-CentOS7上安装Mysql5.7
    MySQL-查看DB文件位置
    游戏编程与游戏种类
    计算机
    python
    python中的构造函数
    IndentationError:expected an indented block错误解决
    python程序的pdb调试方法
  • 原文地址:https://www.cnblogs.com/lexus/p/3529325.html
Copyright © 2011-2022 走看看