Sort a nested dictionary in Python

前端 未结 4 1106
小蘑菇
小蘑菇 2020-12-20 04:53

I have the following dictionary.

var = a = { 
  \'Black\': { \'grams\': 1906, \'price\': 2.05},
  \'Blue\': { \'grams\': 9526, \'price\': 22.88},
  \'Gold\':         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-20 05:10

    Construct an OrderedDict from a list of ordered item tuples:

    from collections import OrderedDict
    
    ordered = OrderedDict(sorted(a.items(), key=lambda i: i[1]['price']))
    

    (.items() assumes Python 3, in Python 2 iteritems should do the same.)

提交回复
热议问题