将文件中的字典存储在嵌套字典中

Store dictionaries from file in nested dictionary

我想从我保存在 TXT 文件中的以下预格式化词典中创建一个嵌套词典。我想将这些附加到新字典中并得到如下结果:

{ "Wednesday": {"Forecast": 18.1, "Visitors": 122}, 
  "Wednesday": {"Forecast": 10.4, "Visitors": 93}, 
  "Wednesday": {"Forecast": 15.6, "Visitors": 105}
}

这就是我在 TXT 文件中存储 data/formatted 词典的方式。

{"Wednesday": {"Forecast": 18.1, "Visitors": 122}}
{"Wednesday": {"Forecast": 10.4, "Visitors": 93}}
{"Wednesday": {"Forecast": 15.6, "Visitors": 105}}

这是我创建一行数据的方式:

write_dict = {Date: {"Forecast": Forecast, "Visitors": Visitors}}

我已经尝试了很多..但仍然无法将此数据转换为简单的嵌套字典。我尝试使用 .update() 将它们添加到一个循环中。然而,这导致嵌套字典只包含最后一个字典。我该怎么办?是不是存储数据的方式不对?

提前致谢! 版本:3.8

编辑:

new_datenumber = ''

def write_data(Visitors):
    with open('numbers.txt', 'r') as file:
        datenumberstr = file.read().rstrip()

    new_datenumber = Date + '_' + datenumberstr
    temp_dict = f'"{new_datenumber}"'+': '+'{"Forecast": '+f'{Forecast}, '+'"Visitors": '+f'{Visitors}'+'}'
    print(new_datenumber)

    datenumber = open('numbers.txt','w')
    datenumber.write(str(int(datenumberstr)+1))
    datenumber.close()

    rest_data = open('rest_data.txt', 'a')
    rest_data.write(f'{temp_dict}\n')
    rest_data.close()

    algorithm_examp()
    return new_datenumber


def algorithm_examp():
    rest_data = open('rest_data.txt', 'r')
    with rest_data as fp:
        newdict = {}
        for line in lines_that_contain(Date, fp):
            no_n_line = line.strip()
            newdict[new_datenumber].update(no_n_line)
            print(newdict)


def lines_that_contain(string, fp):
    return [line for line in fp if string in line]

我希望通过这个得到什么:

{ "Wednesday_1": {"Forecast": 18.1, "Visitors": 122}, 
  "Wednesday_2": {"Forecast": 10.4, "Visitors": 93}, 
  "Wednesday_3": {"Forecast": 15.6, "Visitors": 105}
}

现在数据存储为:

"Wednesday_0": {"Forecast": 18.1, "Visitors": 120}
"Wednesday_1": {"Forecast": 19.5, "Visitors": 125}

我最终找到了另一种存储和使用值的方法:

{"Forecast": 17.8, "Visitors": 95, "Date": "5-20"} # How the data is stored in the txt
        Forecast_n = []
        Visitors_n = []
        for line in lines_that_contain(Date, fp): # check for all lines that contain specfic date
            res = json.loads(line) # convert data string to dictionairy
            print('Date:',res)
            Visitors_n.append(res['Visitors']) # add these values onto a list which i can use to make calculations with.
            Forecast_n.append(res['Forecast']) # add these values onto a list which i can use to make calculations with.

您不能有重复的 'Wednesday' 键,否则只会保存最后一个值。

改变

{"Wednesday": {"Forecast": 18.1, "Visitors": 122}}
{"Wednesday": {"Forecast": 10.4, "Visitors": 93}}
{"Wednesday": {"Forecast": 15.6, "Visitors": 105}}

{"Wednesday_1": {"Forecast": 18.1, "Visitors": 122}}
{"Wednesday_2": {"Forecast": 10.4, "Visitors": 93}}
{"Wednesday_3": {"Forecast": 15.6, "Visitors": 105}}

不能有多个条目具有相同的键。您可以为一个键设置一个条目,并为该键设置一个值列表作为值。所以你可以这样做:

my_dict = defaultdict(list)
with open 'my_txt.txt' as t:
   for line in t:
       try:
          d = eval(line)
          for k in d.keys():
              my_dict[k].append(d[k])
       except Exception as err:
          print('Exception {} occurred while processing {}'.format(err, line))
       

不完全确定输出应该是什么。就规定的要求和样本输出而言,问题存在矛盾。然而:

import json

days = {}
out_dict = {}

with open('rest_data.txt') as fluxx:
    for line in fluxx:
        dict_ = json.loads(line)
        for k, v in dict_.items():
            days[k] = days.get(k, 0) + 1
            out_dict[f'{k}_{days[k]}'] = v

print(out_dict)

输出:

{'Wednesday_1': {'Forecast': 18.1, 'Visitors': 122}, 'Wednesday_2': {'Forecast': 10.4, 'Visitors': 93}, 'Wednesday_3': {'Forecast': 15.6, 'Visitors': 105}}