def taskCompletionCheck(self, jsonFile):
json_data=open(jsonFile)
data = json.load(json_data)
json_data.close()
wsTaskStatus = {}
taskstatus = {}
mydict = {}
''' Assuming the json file structure is similar to
{"tasks":
[{"name":"SA","result":"PASS"},
{"name":"CR","result":"PASS"},
{"name":"UT","result":"fail"}],
"masks":{"id":"valore"},
"om_points":"value",
"parameters":{"id":"valore"}}
'''
for item in data:
keyExists = data[item].get("auto-approve-plugin-status")
if keyExists != None:
for elem in data[item]["auto-approve-plugin-status"] :
mylist = elem["auto-approve-enclosure-names"]
mydict["status"] = elem["auto-approve-status"]
mydict["enclosure-names"] = mylist
taskid = elem["auto-approve-plugin-name"]+"_"+item
taskstatus[taskid] = mydict
print taskstatus
return taskstatus
当我在全局范围内(在for循环之外)声明mydict时,taskstatus不包含mylist的值,enclosure-names只包含o。后来我移动了mydict for循环,它工作正常。谁能解释一下这里发生了什么?
if keyExists != None:
for elem in data[item]["auto-approve-plugin-status"] :
mydict = {}
mylist = elem["auto-approve-enclosure-names"]
mydict["status"] = elem["auto-approve-status"]
mydict["enclosure-names"] = mylist
taskid = elem["auto-approve-plugin-name"]+"_"+item
taskstatus[taskid] = mydict
这就是taskstatus的样子:
{"CR" : {"status" : "fail" , "enclosure-names" : [a,b,c]},
"UT" : {"status" : "pass" , "enclosure-names" : [d,e]}}
答案 0 :(得分:2)
在原始版本中,此代码:
mydict["status"] = elem["auto-approve-status"]
mydict["enclosure-names"] = mylist
每次循环时,你都会重复使用相同的 mydict,每次都会覆盖你在上一个循环中放置的内容。
当您在循环中添加mydict = {}
时,每次循环都会创建一个新的单独字典,然后您不会重复使用或覆盖任何内容并且它可以正常工作。