我是Python的初学者。
我正在检索数据并将其保存到字典中。当第二次循环时,它将替换我的第一个键值。
您可以找到第二个Atfer match_chlDict
的输出,将键"1"
的值替换为键"2"
。
我自己没有办法解决,请帮助。谢谢。
这是match_details ['chl']中的原始照片
[{'LINENUM': '1', 'LINESTATUS': '0', 'LINEORDER': '1', 'LINE': '9.5', 'H': '100@1.75', 'L': '100@1.95'}, {'LINENUM': '2', 'LINESTATUS': '1', 'LINEORDER': '2', 'LINE': '10.5', 'H': '100@2.20', 'L': '100@1.59'}]
代码
match_chl={}
match_chlDict={}
for chl in match_details['chl']:
print("Current match_chlDict")
print(match_chlDict)
match_chl['chlLINE']=chl['LINE']
match_chl['chlH']=replace100(chl['H'])
match_chl['chlL']=replace100(chl['L'])
#Write match_chl to dict by "LINENUM" as key
match_chlDict[chl['LINENUM']]=match_chl
print("Atfer match_chlDict")
print(chl['LINENUM'])
print(match_chlDict)
输出
Curr match_chlDict
{}
获得match_chlDict
1
{'1': {'chlLINE': '9.5', 'chlH': '1.75', 'chlL': '1.95'}}
Curr match_chlDict
{'1': {'chlLINE': '9.5', 'chlH': '1.75', 'chlL': '1.95'}}
获得match_chlDict
2
{'1': {'chlLINE': '10.5', 'chlH': '2.20', 'chlL': '1.59'}, '2': {'chlLINE': '10.5', 'chlH': '2.20', 'chlL': '1.59'}}
答案 0 :(得分:0)
每次循环时都match_chl={}
重新初始化,否则它将替换字典中的引用。
match_chl = {}
match_chlDict = {}
for chl in m:
print("Current match_chlDict")
print(match_chlDict)
match_chl['chlLINE'] = chl['LINE']
match_chl['chlH'] = 'a'
match_chl['chlL'] = 'b'
match_chlDict[chl['LINENUM']] = match_chl
print("Atfer match_chlDict")
print(chl['LINENUM'])
print(match_chlDict)
match_chl = {}
希望这会有所帮助!
答案 1 :(得分:0)
def replace100(str):
return(str.replace("100@",""))
for chl in data:
match_chl = {}
match_chl['chlLINE'] = chl['LINE']
match_chl['chlH'] = replace100(chl['H'])
match_chl['chlL'] = replace100(chl['L'])
match_chlDict[chl['LINENUM']] = match_chl
match_chlDict
我不确定您要寻找什么,但是如果您想将第一个元素用作键,我想上面的代码可以工作。我认为您的错误可能是您将值存储在相同的match_chl
中。您应该在每次循环开始时重置其值。