Sort a nested dictionary in Python

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

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

提交回复
热议问题