在Python中对嵌套字典进行排序

发布于 2021-01-29 14:59:21

我有以下字典。

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

如何根据排序price。因此,结果字典将如下所示。

result = { 
  '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},
  'Magenta': { 'grams': 6035, 'price': 56.69},
  'Mint green': { 'grams': 9961, 'price': 63.89}, 
}
关注者
0
被浏览
98
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    OrderedDict从订购的项目元组列表构造一个:

    from collections import OrderedDict
    
    ordered = OrderedDict(sorted(a.items(), key=lambda i: i[1]['price']))
    

    .items()假设Python 3,在Python 2中iteritems应该做同样的事情。)



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看