Say I have a simple file like so holding arbitrary values:
A, 20, Monday, 14, Tuesday, 15, Tuesday, 16
B, 40, Wednesday, 14, Friday, 12
How would I get it into a nested dictionary so that each k/v pair looks like:
{'A': {'A':'20', 'Monday': '14', 'Tuesday': ['15', '16']},
'B': {'B':'40', 'Wednesday': '14', 'Friday': '12'}}
(If a key error arises from having 'A' and 'B' appear as keys twice, it doesn't matter if the second occurrence of each is replaced with something else.)
My knowledge of nested dictionaries isn't great, so the furthest I've been able to get is reading the lines into a list and having the whole list stored as a value with the key being the first line element.
d = {}
with open (filename) as f:content = f.readlines()for line in content:line = line.strip('\r').strip('\n').split(',')d[line[0]] = line
which returns the output
{'A': ['A', '20', 'Monday', '14', 'Tuesday', '15', 'Tuesday', '16'], 'B':
['B', '40', 'Wednesday', '14', 'Friday', '12']}