在Python中对嵌套字典进行排序 [英] Sort a nested dictionary in Python

查看:351
本文介绍了在Python中对嵌套字典进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字典.

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对其进行排序.因此,结果字典将如下所示.

How can I sort it based on the price. So the resulting dictionary will look like below.

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}, 
}

推荐答案

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

Construct an OrderedDict from a list of ordered item tuples:

from collections import OrderedDict

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

(.items()假定使用Python 3,在Python 2中iteritems应该执行相同的操作.)

(.items() assumes Python 3, in Python 2 iteritems should do the same.)

这篇关于在Python中对嵌套字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆