Sort a nested dictionary in Python

前端 未结 4 1114
小蘑菇
小蘑菇 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:18

    import collections
    
    update=collections.OrderedDict()
    result = sorted(a, key=lambda x: (a[x]['price']))
    for r in result:
        update[r]=a[r]
    
    print(update)
    

提交回复
热议问题