Ordered Dict, preserve initial Order

前端 未结 3 1806
暖寄归人
暖寄归人 2021-01-21 18:42

Ordered Dict:

import collections
d = {\'banana\': 3, \'apple\':4, \'pear\': 1, \'orange\': 2}
collections.OrderedDict(sorted(d.items(), key=lamb         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 19:24

    Already regular dict has no order when you defining.sort on dict is actually not sorting dict.It is sorting the list containing tuples of (key, value) pairs.

    d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
    s = sorted(d.items(), key=lambda t: t[0])
    >>>s
    [('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]
    

    This is sorted list of tuples .key = lambda t: t[0] is returning 2nd element of tuple.So sorting based on 2nd element of tuple

    new_d = dict(s)
    >>>new_d.items()
    [('orange', 2), ('pear', 1), ('apple', 4), ('banana', 3)]
    

    That is order disappears.Inoder to maintain order, OrderedDict is used.

    For example

    >>>OrderedDict({"a":5})
    OrderedDict([('a', 5)])
    

    This is also maintaining list of tuples.

    So you have to pass a sorted list of tuple

    >>>OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
    OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
    

提交回复
热议问题