考慮這個輸入字典:
my_dict = {
'group1':{
'type1': {'val1' : 45, 'val2' : 12, 'val3' : 65},
'type2': {'val5' : 65, 'val6' : 132, 'val7' : 656},
},
'group2':{
'type3': {'val11' : 45, 'val12' : 123, 'val13' : 3},
'type4': {'val51' : 1, 'val61' : 2, 'val71' : 3, },
},
}
我想洗掉最后一個“級別”(只有數字的那個),并得到類似的東西:
new_dict = {
'group1':{
'type1': ['val1', 'val2', 'val3'],
'type2': ['val5', 'val6', 'val7'],
},
'group2':{
'type3': ['val11', 'val12', 'val13'],
'type4': ['val51', 'val61', 'val71'],
},
}
我目前正在通過手動回圈等方式來完成它,但我想知道是否有一種方法可以更有效地完成它。
uj5u.com熱心網友回復:
您沒有給出用于更改 dict 的實際代碼示例,但您可能始終需要 2 級回圈來遍歷組,然后鍵入。就像是:
newdict = {}
for k, grp in my_dict.items():
newdict[k] = {}
for typ, val in grp.items():
newdict[k][typ] = list(val)
提高效率的一種選擇是不預先計算這些更新后的值,而是當您開始使用“組”資料時,list在該點將輸出包裝起來。(雖然很明顯,當使用 dict 時,您仍然會進行迭代,以獲取這些嵌套的 dicts)。
uj5u.com熱心網友回復:
如果您的字典沒有固定數量的嵌套級別,您可以撰寫一個遞回函式來執行此操作:
def stripBottom(d):
if not isinstance(d,dict):
return d
elif not any(isinstance(v,dict) for v in d.values()):
return list(d)
else:
return {k:stripBottom(v) for k,v in d.items()}
輸出:
my_dict = {
'group1':{
'type1': {'val1' : 45, 'val2' : 12, 'val3' : 65},
'type2': {'val5' : 65, 'val6' : 132, 'val7' : 656},
},
'group2':{
'type3': {'val11' : 45, 'val12' : 123, 'val13' : 3},
'type4': {'val51' : 1, 'val61' : 2, 'val71' : 3, },
},
}
print(stripBottom(my_dict))
{'group1': {'type1': ['val1', 'val2', 'val3'],
'type2': ['val5', 'val6', 'val7']},
'group2': {'type3': ['val11', 'val12', 'val13'],
'type4': ['val51', 'val61', 'val71']}}
如果您的字典具有可變級別的嵌套,或者您想洗掉特定級別,則需要向該函式添加一個引數:
def stripBottom(d,level=0):
if not isinstance(d,dict):
return d
elif level == 0:
return list(d)
else:
return {k:stripBottom(v,level-1) for k,v in d.items()}
print(stripBottom(my_dict,1))
{'group1': ['type1', 'type2'], 'group2': ['type3', 'type4']}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363159.html
