我有一个复杂的嵌套字典 - 但我已将我的问题简化为这个玩具示例。添加一个值会跨多个字典这样做,这不是故意的: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条经验 获得超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))
这打印:
{
"60": {
"Green": {
"4": [
"here",
"there"
]
},
"Blue": {
"4": [
"over_there"
]
}
}
}
添加回答
举报
0/150
提交
取消