排序字典键,其中键也是字典

时间:2018-06-28 16:48:45

标签: python python-3.x sorting dictionary

关于如何对这样的字典排序,我有一个简短的问题:

我拥有的是:

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

2 个答案:

答案 0 :(得分:5)

尝试使用内置public class NNodeBeforeLeaf { static Node root; static class Node { int data; Node left, right; Node(int data){ this.data = data; left=right=null; } } public static boolean isLeaf(Node n){ if(n.right == null && n.left == null) return true; return false; } public static void main(String[] args) { int level = 2; // level N root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(8); print(root, 0, level); } public static void print(Node n, int currLevel, int level){ if(n == null){ return; } if(!isLeaf(n)){ print(n.left, currLevel + 1, level); print(n.right, currLevel + 1, level); } printNode(n, currLevel, level); } public static void printNode(Node n, int currLevel, int level){} } 函数的key参数

sorted

注意 我已将您的vehicles_list = sorted([{k:v} for k,v in vehicles.items()], key=lambda x: list(x.values())[0]['speed'], reverse=True) 中的color修改为dict,除非它是您定义的类型,这是错误的

答案 1 :(得分:3)

您可以执行以下操作:

python

另一种解决方案

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