字典中键的排序键 python
Sort key of key in dictionary python
我有一本字典,里面有一些字典。像这样:
Dict= {
"Item1": {"price": 73814.55, "date": f_actual},
"Item2": {"price": 75700, "date": f1},
"Item3": {"price": 84200, "date": f2}
}
我想对属性 'price' 进行排序(从高到低)。我想我可以使用排序函数,但我不知道如何引用“价格”键,因为它们嵌套在 Item1、Item2 等中:
sorted(Dict, key = ??, reverse = True)
所以,我的问题是我该怎么做?还有其他方法吗?
我相信有一种优雅的方式。就等着有人给出 cleaner/faster 解决方案。同时...
print([Dict[i] for i in sorted(Dict, key=lambda item: Dict[item]["price"], reverse=True)])
输出如下
[{'price': 84200, 'date': 'f2'}, {'price': 75700, 'date': 'f1'}, {'price': 73814.55, 'date': 'f_actual'}]
我会这样做:
sorted(Dict.items(), key=lambda x: x[1].get('price'), reverse=True)
请注意,排序对列表对象有意义,但对字典则不然,因为它们基本上是 HashMap。
所以通过这种方式你将得到一个有序的元组列表(键,值),但是如果你想返回到字典来保留一个没有多大意义的顺序。
也请在这里看看这个答案:
How do I sort a dictionary by value?
这对你有用
Dict= {
"Item1": {"price": 73814.55, "date": f_actual},
"Item2": {"price": 75700, "date": f1},
"Item3": {"price": 84200, "date": f2}
}
print(sorted(Dict.items(), key=lambda x: x[1]["price"], reverse=True))
[('Item3', {'price': 84200, 'date': 'f2'}), ('Item2', {'price': 75700, 'date': 'f1'}), ('Item1', {'price': 73814.55, 'date': 'f_actual'})]
我有一本字典,里面有一些字典。像这样:
Dict= {
"Item1": {"price": 73814.55, "date": f_actual},
"Item2": {"price": 75700, "date": f1},
"Item3": {"price": 84200, "date": f2}
}
我想对属性 'price' 进行排序(从高到低)。我想我可以使用排序函数,但我不知道如何引用“价格”键,因为它们嵌套在 Item1、Item2 等中:
sorted(Dict, key = ??, reverse = True)
所以,我的问题是我该怎么做?还有其他方法吗?
我相信有一种优雅的方式。就等着有人给出 cleaner/faster 解决方案。同时...
print([Dict[i] for i in sorted(Dict, key=lambda item: Dict[item]["price"], reverse=True)])
输出如下
[{'price': 84200, 'date': 'f2'}, {'price': 75700, 'date': 'f1'}, {'price': 73814.55, 'date': 'f_actual'}]
我会这样做:
sorted(Dict.items(), key=lambda x: x[1].get('price'), reverse=True)
请注意,排序对列表对象有意义,但对字典则不然,因为它们基本上是 HashMap。
所以通过这种方式你将得到一个有序的元组列表(键,值),但是如果你想返回到字典来保留一个没有多大意义的顺序。
也请在这里看看这个答案: How do I sort a dictionary by value?
这对你有用
Dict= {
"Item1": {"price": 73814.55, "date": f_actual},
"Item2": {"price": 75700, "date": f1},
"Item3": {"price": 84200, "date": f2}
}
print(sorted(Dict.items(), key=lambda x: x[1]["price"], reverse=True))
[('Item3', {'price': 84200, 'date': 'f2'}), ('Item2', {'price': 75700, 'date': 'f1'}), ('Item1', {'price': 73814.55, 'date': 'f_actual'})]