我有一個復雜的嵌套字典 - 但我已將我的問題簡化為這個玩具示例。添加一個值會跨多個字典這樣做,這不是故意的:from collections import defaultdictimport jsonDist_T = defaultdict(lambda:([]))Filter_T = defaultdict(lambda:Dist_T)Phase_T = defaultdict(lambda:Filter_T) Phase_T[60]['Green'][4].append('here')Phase_T[60]['Green'][4].append('there')Phase_T[60]['Blue'][4].append('over_there') #"over-there" will also be appended to the # list for the dictionary of the # Green key which is not intendedprint (json.dumps(Phase_T, indent=2))輸出是:{ "60": { "Green": { "4": [ "here", "there", "over_there" ] }, "Blue": { "4": [ "here", "there", "over_there" ] } } }想要的是:{ "60": { "Green": { "4": [ "here", "there"] }, "Blue": { "4": [ "over_there" ] } } }
1 回答

汪汪一只貓
TA貢獻1898條經(jīng)驗 獲得超8個贊
Phase_T你應該在一行中聲明:
Phase_T = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
Phase_T[60]['Green'][4].append('here')
Phase_T[60]['Green'][4].append('there')
Phase_T[60]['Blue'][4].append('over_there')
print (json.dumps(Phase_T, indent=2))
這打?。?/p>
{
"60": {
"Green": {
"4": [
"here",
"there"
]
},
"Blue": {
"4": [
"over_there"
]
}
}
}
添加回答
舉報
0/150
提交
取消