Sort a nested dictionary in Python

前端 未结 4 2066
臣服心动
臣服心动 2020-12-20 04:33

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:20

    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.)

提交回复
热议问题