Sort a nested dictionary in Python

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

    You can also use getitem from the operator library:

    from collections import OrderedDict
    from operator import getitem
    
    sorted_dict = OrderedDict(sorted(a.items(), key = lambda x:getitem(x[1],'price')))
    
    print(sorted_dict)
    

    Output:

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

提交回复
热议问题