我有一个要在dict内创建dict的数据列表,其结构按预期进行,但是在某些地方被覆盖,我不知道在哪里
a=['t1_h1','t2_h2']
b=['h1_d1','h1_d2','h2_d3']
c=['d1_dom1','d2_dom2','d3_dom3']
d=['dom1_a','dom1_b','dom2_a','dom2_b','dom3_a','dom3_b']
我尝试使用此代码
for item in a:
f[item.split('_')[0]]={}
for hypercube in b:
if item.split('_')[1] in hypercube:#h1 in b
f[item.split('_')[0]][item.split('_')[1]]={}
for dimension in c:
if hypercube.split('_')[1] in dimension:#d1 in c
f[item.split('_')[0]][item.split('_')[1]][hypercube.split('_')[1]]={}
for domain in d:
if dimension.split('_')[1] in domain:#dom1 in d
if f[item.split('_')[0]][item.split('_')[1]][hypercube.split('_')[1]].has_key(dimension.split('_')[1]):
f[item.split('_')[0]][item.split('_')[1]][hypercube.split('_')[1]][dimension.split('_')[1]].append(domain.split('_')[1])
else:
f[item.split('_')[0]][item.split('_')[1]][hypercube.split('_')[1]][dimension.split('_')[1]]=[domain.split('_')[1]]
实际上,我正在尝试以这种格式打印:
{'t1': {'h1': {'d1': {'dom1': ['a', 'b']}, 'd2': {'dom2': ['a', 'b']}}},
't2': {'h2': {'d3': {'dom3': ['a', 'b']}}}}
但是我得到的输出是:
{'t2': {'h2': {'d3': {'dom3': ['a','b']}}}, 't1': {'h1': {'d2': {'dom2': ['a','b']}}}}
但更改完最后一件事后,便是't1''d1'值缺失
最佳答案
您不想嵌套for循环,而是想在处理每个列表a,b,c和d时嵌套for搜索,从而为f增加了越来越深的层次。这将提供所需的输出:
f = {}
for item in a:
ak1,ak2 = item.split('_')
f[ak1] = {ak2:{}}
for item in b:
bk1,bk2 = item.split('_')
next(f[akey][bk1]
for akey in f
if bk1 in f[akey])[bk2] = {}
for item in c:
ck1,ck2 = item.split('_')
next(f[akey][bkey][ck1]
for akey in f
for bkey in f[akey]
if ck1 in f[akey][bkey])[ck2] = []
for item in d:
dk1,dk2 = item.split('_')
next(f[akey][bkey][ckey][dk1]
for akey in f
for bkey in f[akey]
for ckey in f[akey][bkey]
if dk1 in f[akey][bkey][ckey]).append(dk2)
import pprint
pprint.pprint(f)
印刷品:
{'t1': {'h1': {'d1': {'dom1': ['a', 'b']}, 'd2': {'dom2': ['a', 'b']}}},
't2': {'h2': {'d3': {'dom3': ['a', 'b']}}}}
关于python - 如何在不覆盖旧数据的情况下在另一个dict中创建dict,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10980136/