我这里有一本有结构的字典
'set1':{ 'status': 1,
'data': {'1': {'C': ['116.587',
'52.674',
'23.164',
'8.5'],
<sth>:...},
{'2': {'C': ['11.507',
'50.674',
'23.004',
'8.02'],
<sth>:...},
{'3': {'C': ['16.587',
'2.674',
'3.164',
'0.5'],
<sth>:...}
{'4': {'C': ['0.587',
'1.674',
'3.009',
'0.55'],
<sth>:...}
'set2':{ 'status': 1,
'data': {'3': {'C': ['116.587',
'52.674',
'23.164',
'8.5'],
<sth>:...}
#<goes like this>
我需要将所有通道的信息存储在 C 下,所有通道 '1'、'2'、'3' 和 '4' 超过 100k。但并非所有的集合都有 4 个通道,但只有“3”和“4”,或者只有“1”和“2”。我试图用零填充不存在的通道。
我尝试使用这个语句if( idict[n]["data"][c] ):
我认为如果这是真的,例如 idict["set1"]["data"]["1"] 是真的,它应该填充通道 '1',否则它应该填充 '0.000'。
idict 是输入字典,odict 是输出字典
for n in idict: #n is the set number
try:
if(idict[n]["status"]==1 and idict[n]["data"]):
#some has status=0 or has no data key. I need to ignore those
odict[n] = []
for c in ('1','2','3','4'):
if( idict[n]["data"][c] ): #THIS IS WHAT I USED FOR THIS ISSUE
odict[n].append({
c : [
str(idict[n]["data"][c]["C"][0]),
str(idict[n]["data"][c]["C"][1]),
str(idict[n]["data"][c]["C"][2]),
str(idict[n]["data"][c]["C"][3])
]
#indicies after ["C"] are for the 4 non integer entries
})
else:
odict[n].append({
c : ['0.000','0.000','0.000','0.000']
})
except KeyError:
continue
输出应该是这样的
'set1':{
{'1': ['116.587','52.674','23.164','8.5']
{'2': ['11.507','50.674','23.004','8.02']
{'3': ['16.587','2.674','3.164','0.5']
{'4': ['0.587','1.674','3.009','0.55']
}
'set2':{
'3': ['116.587','52.674,'23.164','8.5'],
'4': [<something similar>]
}
#<goes like this>
但是对于缺少某些频道的集合,我得到了空字典,但是有 4 个频道的集合已被填满。
感谢任何帮助。
我已经找到了。代替
if( idict[n]["data"][c] ):
我应该用
if c in idict[str(n)]["data"]:
现在它起作用了。
感谢所有的努力。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句