Home > other >  Store dictionaries from file in nested dictionary
Store dictionaries from file in nested dictionary

Time:05-17

I want to create a nested dictionairy out of the following pre-formatted dictionaries that i saved in a TXT file. I want to append these to a new dictionary and get a result like this:

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

This is how I have stored the data/formatted dictionaries in the TXT file.

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

This is how I create a line of data:

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

I have tried a lot.. and still wasnt able to convert this data into a simple nested dictionary. I tried adding these in a loop with .update(). This however resulted in the nested dictionairy only containing the last dictionairy. What do I do? Is the way of storing the data possibly wrong?

Thanks in advance! Version: 3.8

Edit:

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]

What i hope to get with this:

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

Right now the data is being stored as:

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

CodePudding user response:

You cannot have duplicate 'Wednesday' keys, or else only the last value will be saved.

change

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

to

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

CodePudding user response:

You can't have multiple entries with same key. You can have one entry for one key and a list of values as value for that key. So you can do something like:

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

CodePudding user response:

Not entirely sure what the output is supposed to be. There are contradictions in the question in terms of the stated requirement and the sample output. However:

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)

Output:

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