I have a text file that is very unorganized with multiple-sub-index objects, something like this:
1:
Name of Object 1
Sub-index 0:
Scale: Q0
Unit: Percent
Description: Object 1 does this
2:
Object 2 yo
Sub-index 0:
Scale: Q0
Unit: Percent
Description: Something important
Sub-index 1:
Scale: 0.125
Unit: Percent
Description: Object 2 does that
I want to extract these objects' name, scale and description and make them into a dictionary. Something like this:
ObjectDict = {
1: ['Name of Object 1', 'Q0', 'Object 1 does this'],
2: {
0: ['Object 2 yo', 'Q0', 'Something important'],
1: ['Object 2 yo', '0.125', 'Object 2 does that']
}
}
I was able to extract the dictionary keys by doing this:
for line in textfile:
a = line.replace(':', '')
if b.isnumeric():
# this is 1 key
I can "probably" extract Scale and Description value of an object by doing:
if 'Scale' in line: # Store the value
if 'Description' in line: # Store the value
However, this would only work if the object only has 1 sub-index. For multiple-sub-index objects like Object 2, I could not figure out how to do them yet. Is there a nice way to do this in Python 3.7? Thanks!
EDIT: The dictionary format I chose above is just an example. Any other formatted dictionary is okay. I just want to extract necessary data from an unorganized file and store it more properly so other files can access them.
1be a list but the value for2be a dict doesn't sound like a good idea. Just save a dict with one item. Second, indexing dicts with integers is rarely justified. If that's your usecase, just use lists.if 'Sub-index' in lineand then just do what you said. But think again about your chosen structure.