我有以下結構:
d = {
'futures': {
'test': {
'nested': {
1: {
'list': [
{
'c': 'third',
'price': 3
},
{
'b': 'second',
'price': 2
},
{
'a': 'first',
'price': 1
}
]
},
2: {
'list': [
{
'f': 'sixth',
'price': 6
},
{
'e': 'fifth',
'price': 5
},
{
'd': 'fourth',
'price': 4
}
]
}
}
}
}
}
我需要按價格對每個串列進行排序,升序。結果應該是:
d = {
'futures': {
'test': {
'nested': {
1: {
'list': [
{
'a': 'first',
'price': 1
},
{
'b': 'second',
'price': 2
},
{
'c': 'third',
'price': 3
},
]
},
2: {
'list': [
{
'd': 'fourth',
'price': 4
},
{
'e': 'fifth',
'price': 5
},
{
'f': 'sixth',
'price': 6
}
]
}
}
}
}
}
由于這種特殊的結構,我發現的所有問題都不適合我的需求。
有沒有辦法訂購它而不必訪問每個以前的鍵?因為在我的專案中,我在串列之前有更多嵌套鍵的案例,所以我需要一個動態解決方案來對其進行排序。我的意思是,我不知道串列的確切路徑,只知道串列鍵。
uj5u.com熱心網友回復:
創建一個函式來遞回遍歷您的dict查找串列,并根據您的條件對每個串列進行排序:
def find_and_sort_lists(d):
for value in d.values():
if isinstance(value, list):
value.sort(key = lambda nested_d: nested_d['price'])
if isinstance(value, dict):
find_and_sort_lists(value)
如果需要僅對 key 實際上為 的串列進行排序'list',則可以使用以下命令:
def find_and_sort_lists(d):
for key, value in d.items():
if key == 'list' and isinstance(value, list):
value.sort(key = lambda nested_d: nested_d['price'])
if isinstance(value, dict):
find_and_sort_lists(value)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410038.html
標籤:
下一篇:如何合并具有相同值的字典鍵?
