Read a file into a nested dictionary?

2024/10/9 9:22:36

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']}
Answer

Here you go:

with open(filename) as f:lines = f.readlines()output = {}for s in lines: split_line = s.split(",")first = split_line[0].strip()output[first] = {}output[first][first] = split_line[1].strip()pairs = []for i in range(0, len(split_line[2:]), 2):pairs.append(split_line[2:][i:i+2])for pair in pairs:day = pair[0].strip()output[first].setdefault(day, []).append(pair[1].strip())print output

The output looks like this:

{'A': {'A': '20', 'Tuesday': ['15', '16'], 'Monday': ['14']}, 'B': {'B': '40', 'Friday': ['12'], 'Wednesday': ['14']}}
https://en.xdnf.cn/q/118601.html

Related Q&A

Using .replace function

I have a code with more than 2500 lines that contains several references to GIS layers. I need to replace these layers in the code for several web maps so I have to find a way to automate a find and re…

Python Turtle unit of measurement

When we instantiate a turtle object, we can draw a circle. I wonder about the radius parameter of the circle() method. import turtle myTurtle = turtle.Turtle() myTurtle.circle(50)What is the unit of me…

Python reverse() vs [::-1] slice performance [duplicate]

This question already has answers here:Difference between reverse and [::-1](2 answers)Time complexity of reversed() in Python 3(1 answer)Closed last year.Python provides two ways to reverse a list: Li…

Django Callback on Facebook Credits

I would like to use Facebook Credits with my Django Application.In the Facebook Credits documentation, there is only a sample for the callback page in PHP (https://developers.facebook.com/blog/post/489…

Remove \n from each string stored in a python list

I have a python list in which look like this:my_list = [OFAC\n, Social Media Analytics\n, Teaching Skills\n, Territory...\n, Active Directory...\n, Business Research\n, Call Center...\n, Treatment of d…

Optimizing loop. Faster ResultList.append( [ c, d, c[1]/d[1]] )? Array? Map?

The following works well but Id like to make it faster. The actual application could process Tuple1 and Tuple2 each with 30,000 elements and 17 nested sequences per element. I see numerous questions …

Why do I get an error name play is not defined when I think it is?

Full error: line 10, in <module>colour = play() NameError: name play is not definedI cant seem to find a reason for this issue anywhere on here. I am trying to assign the returned string to the v…

Error: unhashable type: dict

i have a problem with Django: I cant show the data from mysql database in the table. I see the error "Exception Value: unhashable type: dict" This is my code: views.py:List_of_date=El.objects…

terminal command line python3.3

Im following a book tutorial and its telling me to install python3.3 with the command linesudo apt-get install python3.3however Im getting errorsUnable to locate package python3.3 Couldnt find any pack…

SQLalchemy making errors after being updated to 1.4.0 [duplicate]

This question already has answers here:ImportError: cannot import name _ColumnEntity from sqlalchemy.orm.query(5 answers)ImportError: cannot import name _ColumnEntity Ubuntu20.10 [duplicate](1 answer)C…