简体   繁体   English

将值附加到字典的相同键中

[英]Append values in the same key of a dictionary

How to add different values in the same key of a dictionary? 如何在字典的同一键中添加不同的值? These different values are added in a loop. 这些不同的值被循环添加。

Below is what I desired entries in the dictionary data_dict 以下是我希望在字典data_dict输入的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

However, at the end of the iterations, data_dict is left with the last entry only: 但是,在迭代结束时,data_dict只剩下最后一个条目:

{'HUBER': {'80': 5.50}}

Here's the code: 这是代码:

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()

You can use dict.setdefault here. 您可以在此处使用dict.setdefault Currently the problem with your code is that in each call to func_ you're re-assigning data_dict["HUBER"] to a new dict. 当前,您的代码存在的问题是,在每次对func_调用中,您都在将data_dict["HUBER"]重新分配给新的dict。

Change: 更改:

data_dict["HUBER"] = {points: mean_error}

to: 至:

data_dict.setdefault("HUBER", {})[points] = mean_error

You can use defaultdict from the collections module: 您可以从collections模块使用defaultdict:

import collections

d = collections.defaultdict(dict)
d['HUBER']['100'] = 5.42
d['HUBER']['10'] = 3.45

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM