如何在字典的同一个键中添加不同的值?添加了这些不同的值 在一个循环中。
以下是字典data_dict
data_dict = {}
And during each iterations, output should looks like:
Iteration1 -> {'HUBER': {'100': 5.42}}
Iteration2 -> {'HUBER': {'100': 5.42, '10': 8.34}}
Iteration3 -> {'HUBER': {'100': 5.42, '10': 8.34, '20': 7.75}} etc
但是,在迭代结束时,data_dict仅留下最后一个条目:
{'HUBER': {'80': 5.50}}
以下是代码:
import glob
path = "./meanFilesRun2/*.txt"
all_files = glob.glob(path)
data_dict = {}
def func_(all_lines, method, points, data_dict):
if method == "HUBER":
mean_error = float(all_lines[-1]) # end of the file contains total_error
data_dict["HUBER"] = {points: mean_error}
return data_dict
elif method == "L1":
mean_error = float(all_lines[-1])
data_dict["L1"] = {points: mean_error}
return data_dict
for file_ in all_files:
lineMthds = file_.split("_")[1] # reading line methods like "HUBER/L1/L2..."
algoNum = file_.split("_")[-2] # reading diff. algos number used like "1/2.."
points = file_.split("_")[2] # diff. points used like "10/20/30..."
if algoNum == "1":
FI = open(file_, "r")
all_lines = FI.readlines()
data_dict = func_(all_lines, lineMthds, points, data_dict)
print data_dict
FI.close()
答案 0 :(得分:2)
您可以在此处使用dict.setdefault
。目前,您的代码存在的问题是,在每次致电func_
时,您都会将data_dict["HUBER"]
重新分配给新的字典。
变化:
data_dict["HUBER"] = {points: mean_error}
为:
data_dict.setdefault("HUBER", {})[points] = mean_error
答案 1 :(得分:1)
您可以使用集合模块中的defaultdict:
import collections
d = collections.defaultdict(dict)
d['HUBER']['100'] = 5.42
d['HUBER']['10'] = 3.45