Reputation: 432
I have a list that looks like this:
ls = [
{
"max_supply": None,
"platform": None,
"quote": {
"USD": {
"fully_diluted_market_cap": 464800388135.72,
"last_updated": "2021-10-20T13:37:02.000Z",
"market_cap": 464800388135.7246,
"price": 3938.871641392752,
"volume_24h": 15411634916.820467,
"volume_change_24h": -3.4909
}
}
},
{
"max_supply": None,
"platform": None,
"quote": {
"USD": {
"fully_diluted_market_cap": 58764548678.52,
"last_updated": "2021-10-20T13:37:03.000Z",
"market_cap": 58764548678.52,
"price": 4784.77,
"volume_24h": 189992412916.647,
"volume_change_24h": 85.422
}
}
},
]
How do I order the given list by each market_cap
value that is located in the quote
and USD
keys?
I have found some solutions but they are only referring to sort by the first-level dictionary keys and values, however I have not been able to find any solutions for sorting by the keys and values in a dictionary two-level deep. in the given list.
Upvotes: 2
Views: 540
Reputation: 24018
You can pass a lambda function as the key
argument for the built-in sorted
function:
ls = [
{
"max_supply": None,
"platform": None,
"quote": {
"USD": {
"fully_diluted_market_cap": 464800388135.72,
"last_updated": "2021-10-20T13:37:02.000Z",
"market_cap": 464800388135.7246,
"price": 3938.871641392752,
"volume_24h": 15411634916.820467,
"volume_change_24h": -3.4909
}
}
},
{
"max_supply": None,
"platform": None,
"quote": {
"USD": {
"fully_diluted_market_cap": 58764548678.52,
"last_updated": "2021-10-20T13:37:03.000Z",
"market_cap": 58764548678.52,
"price": 4784.77,
"volume_24h": 189992412916.647,
"volume_change_24h": 85.422
}
}
},
]
sorted_ls = sorted(ls, key=lambda obj: obj["quote"]["USD"]["market_cap"])
Alternatively, you can use the .sort()
method if you want to edit the list in-place.
Upvotes: 3
Reputation: 4823
You can define your own function that returns a key to sort against and then use sort
like so
all_data = [
{
"max_supply": null,
"platform": null,
"quote": {
"USD": {
"fully_diluted_market_cap": 464800388135.72,
"last_updated": "2021-10-20T13:37:02.000Z",
"market_cap": 464800388135.7246,
"price": 3938.871641392752,
"volume_24h": 15411634916.820467,
"volume_change_24h": -3.4909
}
}
},
{
"max_supply": null,
"platform": null,
"quote": {
"USD": {
"fully_diluted_market_cap": 58764548678.52,
"last_updated": "2021-10-20T13:37:03.000Z",
"market_cap": 58764548678.52,
"price": 4784.77,
"volume_24h": 189992412916.647,
"volume_change_24h": 85.422
}
}
},
]
def get_sort_key(current_dict):
return current_dict['quote']['USD']['market_cap']
all_data.sort(key=get_sort_key)
print(f'Sorted dict: {all_data}')
Upvotes: 2