[英]How to sort a list of nested dictionaries based on a deeply nested key?
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?如何按位于
quote
和USD
键中的每个市场market_cap
值对给定列表进行market_cap
?
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.
在给定的列表中。
You can pass a lambda function as the key
argument for the built-in sorted
function:您可以传递一个 lambda 函数作为内置
sorted
函数的key
参数:
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.或者,如果您想就地编辑列表,您可以使用
.sort()
方法。
You can define your own function that returns a key to sort against and then use sort
like so您可以定义自己的函数,该函数返回要排序的键,然后像这样使用
sort
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}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.