【问题标题】:Sort dictionary keys where the key is also a dictionary排序字典键,其中键也是字典
【发布时间】:2018-12-07 20:02:53
【问题描述】:

我有一个关于如何像这样对字典进行排序的快速问题:

我拥有的是:

vehicles = {"carA": {"speed": 20, "color": "red"}, "carB": {"speed": 25, "color": "blue"}}

我想要的是一个列表,其中车辆字典按速度的高位排序(carB 的速度高于 carA 的速度,因此 carB 是列表中的第一个):

vehicles_list = [{"carB": {"speed": 25, color: "blue"}}, {"carA": {"speed": 20, color: "red"}}]

【问题讨论】:

  • 为什么将这些存储为嵌套字典而不是具有速度和颜色类变量的汽车类?
  • @emsimpson92 不仅可以作为一个例子,而且如果只有数据(例如汽车经销商的数据库),构建一个类真的是时间/空间效率低下
  • 另外,如果您正在序列化/反序列化这些值,字典可以非常干净地与 json 进行转换,而且开销很小。因此,将数据保存为嵌套字​​典不仅是 Python 式的,而且非常干净和高效。
  • 我明白了。我没有考虑过json

标签: python python-3.x sorting dictionary


【解决方案1】:

尝试使用内置 sorted 函数的 key 参数

vehicles_list = sorted([{k:v} for k,v in vehicles.items()], 
                       key=lambda x: list(x.values())[0]['speed'],
                       reverse=True)

注意 我已将您的dict 中的color 修改为string,除非它是您定义的类型,否则这是一个错误

【讨论】:

  • 你能补充一下吗
【解决方案2】:

您可以执行以下操作:

import operator
list_of_dicts = list(vehicles)
list_of_dicts.sort(key=operator.itemgetter('speed'), reverse=True)

另一种解决方案

from collections import OrderedDict 
order_dic = list(OrderedDict(sorted(dic.items(), key=lambda x: x[1]['speed'], reverse=True)))

【讨论】:

  • 当我尝试这个时,我得到一个 TypeError: string indices must be integers
  • 我明白了。让我知道更新新方式是否适合您。我的第一个解决方案是对字典列表进行排序。
  • 您的第二个解决方案只生成一个列表,其中包含没有其值的 dict 键。
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 2021-11-27
  • 2011-06-17
  • 1970-01-01
  • 2017-08-20
  • 2011-01-25
  • 1970-01-01
相关资源
最近更新 更多