美文网首页
Python collections模块--OrderedDic

Python collections模块--OrderedDic

作者: SateZheng | 来源:发表于2017-01-09 15:34 被阅读198次

    OrderedDict 有序字典

    字典是无序的,可以通过OrderedDict使其有序。当对字典做迭代时,它会严格按照元素的初始的添加的顺序进行。

    In [60]: o1 = collections.OrderedDict()
    
    In [79]: o1['foo'] = 1
    
    In [80]: o1['bar'] = 2
    
    In [81]: o1['spam'] = 3
    
    In [82]: o1['grok'] = 4
    
    In [83]: o1['aa'] = 5
    
    In [84]: o1
    Out[84]: OrderedDict([('foo', 1), ('bar', 2), ('spam', 3), ('grok', 4), ('aa', 5)])
    
    In [87]: for key in o1:
        ...:     print key, o1[key]
        ...:
    foo 1
    bar 2
    spam 3
    grok 4
    aa 5
    

    由于有序字典会记住其插入顺序,因此可以与排序结合使用以创建排序字典

    >>> # 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)])
    

    相关文章

      网友评论

          本文标题:Python collections模块--OrderedDic

          本文链接:https://www.haomeiwen.com/subject/ujlhbttx.html