Home > Net >  Sort python list with dictionaries based on the last value of another nested dictionary
Sort python list with dictionaries based on the last value of another nested dictionary

Time:10-05

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

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

CodePudding user response:

see below (using lambda as a key)

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

[{'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}]}]
  • Related