+ 2

How to Create multiple nested dictionary from a file?

I have a txt file and the content of the file is like this: [General statistics] Lines of input read 68258 Variants processed 68258 [Variant classes] indel 31 sequence_alteration 388 I want to create a dictionary from this file like this: {'General statistics':{'Lines of input read': 68258, 'Variants processed': 68258}, 'General statistics':{'indel': 31, 'sequence_alteration': 388}}

29th Jun 2022, 2:27 PM
Baran Aldemir
Baran Aldemir - avatar
4 Answers
+ 1
there is a lot of aproache to this, the trick is to take it step by step. 1. you know that there are multiple sections, they all starts and end with brackets. Can you retrieve the text from those? for line in lines: if(line.startswith("[") and line.endswith("]")): print("section is: " + line) 2. can you find a value and it's name for line in lines: if(len(line.split(" ")) == 2): print("name is: " + line.split(" ")[0]) print("value is " + line.split(" ")[1]) I'll stop writing here, my code isn't checked so make sure it works for you. anyway, with this info you should be able to put your code together more easily I hope this helps :)
29th Jun 2022, 2:41 PM
Apollo-Roboto
Apollo-Roboto - avatar
+ 5
Baran Aldemir , that sounds interesting. but before giving you some hints, i need some more information from you: -> let's say we have a code that can read the *.txt file and create a dictionary as you mentioned. what is the purpose of this dict? -> how many different "categories" can occur (like [general statistics], [variant classes], ...) -> how is the dict used and how often it will be accessed? -> do you need to keep this dict with its data for further use? -> how often do you need to repeat the procedure of reading a text file? -> do you need to search for any data in the dictionary? -> do you need to use the data for statistical purposes? -> do you need to export data or a part of it? i am asking this because collections of dictionaries may not the preferred way to handle and store this kind of data.may be a database could be a solution?
29th Jun 2022, 3:20 PM
Lothar
Lothar - avatar
+ 2
Thank you for both of you guys. I managed to create the dictionary I wanted. This file is for a project and I've also created JSON files from this dictionary. I was struggling with some for loops but after @Apollo-Roboto I realized a more straightforward solution.
30th Jun 2022, 5:44 PM
Baran Aldemir
Baran Aldemir - avatar
+ 2
Btw, I have to say SoloLearn and its community are really awesome. Other websites like StackOverflow are not that friendly for people who are asking their questions. After a while, they got my permission to ask questions and it's really not easy to get your permission back there. I am really grateful for the community and administration here.
30th Jun 2022, 5:50 PM
Baran Aldemir
Baran Aldemir - avatar