I'm trying to read in data from and create a nested dictionary of dictionaries. There is a similar question here, but I can't seem to figure out how to adapt a solution to my particular problem. I would be very grateful if someone could explain a solution to me for my problem.
Basically, I have a file that looks like this:
A 'abc' 12 0.001
B 'tex' 34 0.002
B 'tex' 78 0.005
E 'yet' 88 0.090
A 'abc' 22 0.120
I need to create a complex dictionary that looks like this:
complete_dict = {A:{'abc':[[12, 0.001], [22, 0.120]]},
B:{'tex':[[34, 0.002], [78, 0.005]]},
E:{'yet':[[88, 0.090]]}}
I can create the inner dictionary, but I can't figure out how to create the outer dictionary. Here is my code for the inner dictionary:
with open('data.txt', mode="r") as data_file:
fieldnames = ('character', 'string', 'value1', 'value2')
reader = csv.DictReader(data_file, fieldnames=fieldnames, delimiter="\t")
inner_dict = {}
for row in reader:
values = [int(row['value1']), float(row['value2'])]
string = row['string']
if string in inner_dict:
inner_dict[string].append(values)
else:
inner_dict[string] = values
Could someone explain how to create the outer dictionary? The only idea I have is to read the file and create the inner dictionary, then reread the file to create the outer dictionary. Surely there must be an easier way? Thanks in advance for the help!