Ordered Dict, preserve initial Order

前端 未结 3 1805
暖寄归人
暖寄归人 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:09

    Once you initialized regular dict with your items the order is gone. So just initialize ordered dict in initial order:

    import collections as co
    
    co.OrderedDict([(a, b) for a, b in list_of_pairs])
    # or
    d = co.OrderedDict()
    for a, b in list_of_pairs:
        d[a] = b
    

提交回复
热议问题