[英]Sort python list with dictionaries based on the last value of another nested dictionary
I have a complex list with dictionaries which consist of other dictionaries.我有一个复杂的列表,其中包含由其他词典组成的词典。 I need to sort the following list according to the last y value so that the USD data comes first after AUD data.
我需要根据最后一个y值对以下列表进行排序,以便美元数据排在澳元数据之后。 The last of value for USD is 4 and the last value of AUD is 3, so USD should be the first dictionary in the list and AUD should be the second dictionary in the list.
USD 的最后一个值是 4,AUD 的最后一个值是 3,所以 USD 应该是列表中的第一个字典,AUD 应该是列表中的第二个字典。
I would appreciate any advice on how this can be achieved.我将不胜感激有关如何实现这一目标的任何建议。
Here is the original list:这是原始列表:
[
{
"instrument": "AUD",
"changes": [
{"x": 1632765600000, "y": 0},
{"x": 1632769200000, "y": 1},
{"x": 1632772800000, "y": 2},
{"x": 1632776400000, "y": 3},
]
},
{
"instrument": "USD",
"changes": [
{"x": 1632765600000, "y": 0},
{"x": 1632769200000, "y": 2},
{"x": 1632772800000, "y": 3},
{"x": 1632776400000, "y": 4},
]
},
]
This is the result I'm willing to obtain:这是我愿意得到的结果:
[
{
"instrument": "USD",
"changes": [
{"x": 1632765600000, "y": 0},
{"x": 1632769200000, "y": 2},
{"x": 1632772800000, "y": 3},
{"x": 1632776400000, "y": 4},
]
},
{
"instrument": "AUD",
"changes": [
{"x": 1632765600000, "y": 0},
{"x": 1632769200000, "y": 1},
{"x": 1632772800000, "y": 2},
{"x": 1632776400000, "y": 3},
]
},
]
see below (using lambda
as a key)见下文(使用
lambda
作为密钥)
data = [
{
"instrument": "AUD",
"changes": [
{"x": 1632765600000, "y": 0},
{"x": 1632769200000, "y": 1},
{"x": 1632772800000, "y": 2},
{"x": 1632776400000, "y": 3},
]
},
{
"instrument": "USD",
"changes": [
{"x": 1632765600000, "y": 0},
{"x": 1632769200000, "y": 2},
{"x": 1632772800000, "y": 3},
{"x": 1632776400000, "y": 4},
]
}
]
data = sorted(data, key = lambda x : x['changes'][-1]['y'],reverse=True)
print()
print(data)
print()
output output
[{'instrument': 'USD', 'changes': [{'x': 1632765600000, 'y': 0}, {'x': 1632769200000, 'y': 2}, {'x': 1632772800000, 'y': 3}, {'x': 1632776400000, 'y': 4}]}, {'instrument': 'AUD', 'changes': [{'x': 1632765600000, 'y': 0}, {'x': 1632769200000, 'y': 1}, {'x': 1632772800000, 'y': 2}, {'x': 1632776400000, 'y': 3}]}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.