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

标签 python sorting dictionary hashtable

我有以下字典。

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

如何根据价格对其进行排序。因此生成的字典将如下所示。

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:

from collections import OrderedDict

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

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

关于python - 在 Python 中对嵌套字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38095250/

相关文章:

ios - 里面有数组的数组

python - 输出不按行显示

Python 模式循环

javascript - 对除第一项之外的数组进行排序。 Array.prototype.sort()

java - 如果 key1 具有相同的值,如何按 key1 降序和 key2 升序对 List<Map<String,String>> 进行排序

xcode - Swift 2.0 map "Instance member cannot be used on type"

python - 当我试图捕获多个异常时省略括号会发生什么?

python - 如何在 Python 中使用 PCA 来构建术语文档矩阵?

C# - 如何通过 linq 对列表字符串编号进行排序?

python - Python随机输出一个字典条目,如何临时删除?