zoukankan      html  css  js  c++  java
  • 8.3. collections — Highperformance container datatypes — Python v2.7.3 documentation

    8.3. collections — High-performance container datatypes — Python v2.7.3 documentation

    OrderedDict Examples and Recipes

    Since an ordered dictionary remembers its insertion order, it can be used in conjuction 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 Counter class so that the counter remembers the order elements are first encountered:

  • 相关阅读:
    我爱工程化 之 gulp 使用(二)
    我爱工程化 之 gulp 使用(一)
    用户体验之输入框设想
    SEO优化
    js代码优化
    RequireJs 依赖管理使用
    Git 安装与使用(一)
    Webstorm 配置与使用 Less
    Less使用——让老司机带你飞
    Node安装与环境配置
  • 原文地址:https://www.cnblogs.com/lexus/p/2773263.html
Copyright © 2011-2022 走看看