Sort a nested dictionary in Python

前端 未结 4 1729
臣服心动
臣服心动 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:37

    for s in sorted(a.iteritems(), key=lambda (x, y): y['price']):
           print s
    

    Or by OrderedDict

    from collections import OrderedDict
    res = OrderedDict(sorted(a.items(), key=lambda x: x[1]['price'], reverse=False))
    print res
    

    Output:

    [('Black', {'price': 2.05, 'grams': 1906}), ('Gold', {'price': 8.24, 'grams': 194}), ('Orchid', {'price': 10.78, 'grams': 4970}), ('Maroon', {'price': 18.76, 'grams': 922}), ('Blue', {'price': 22.88, 'grams': 9526}), ('Tan', {'price': 50.54, 'grams': 6738}), ('Yellow', {'price': 54.19, 'grams': 6045}), ('Magenta', {'price': 56.69, 'grams': 6035}), ('Mint green', {'price': 63.89, 'grams': 9961})]
    

提交回复
热议问题