How to parse a text file into a dictionary in python with key on one line followed by two lines of values

Viewed 60

I have a file with lines in this format:

CALSPHERE 1             
1 00900U 64063C   20161.15561498  .00000210  00000-0  21550-3 0  9996
2 00900  90.1544  28.2623 0029666  80.8701  43.4270 13.73380512769319
CALSPHERE 2             
1 00902U 64063E   20161.16836122  .00000025  00000-0  23933-4 0  9990
2 00902  90.1649  30.9038 0019837 126.9344   3.6737 13.52683749559421

..etc.

I would like to parse this into a dictionary of the format:

{CALSPHERE 1:(1 00900U 64063C   20161.15561498  .00000210  00000-0  21550-3 0  9996, 2 00900  90.1544  28.2623 0029666  80.8701  43.4270 13.73380512769319),
CALSPHERE 2:(1 00902U 64063E   20161.16836122  .00000025  00000-0  23933-4 0  9990, 2 00902  90.1649  30.9038 0019837 126.9344   3.6737 13.52683749559421),...}

I'm puzzled as to how to parse this, so that every third line is the key, with the following two lines forming a tuple for the value. What would be the best way to do this in python?

I've attempted to add some logic for "every third line" though it seems kind of convoluted; something like

    with open(r"file") as f:
        i = 3
        for line in f:
             if i%3=0:
                key = line
             else:
                #not sure what to do with the next lines here
2 Answers

If your file always have the same distribution (i.e: the 'CALSPHERE' word -or any other that you want it as your dictionary key-, followed by two lines), you can achieve what you want by doing something as follows:

with open(filename) as file:
    lines = file.read().splitlines()
    d = dict()
    for i in range(0, len(lines), 3):
        d[lines[i].strip()] = (lines[i + 1], lines[i + 2])

Output:

{
    'CALSPHERE 1': ('1 00900U 64063C   20161.15561498  .00000210  00000-0  21550-3 0  9996', '2 00900  90.1544  28.2623 0029666  80.8701  43.4270 13.73380512769319'),
    'CALSPHERE 2': ('1 00902U 64063E   20161.16836122  .00000025  00000-0  23933-4 0  9990', '2 00902  90.1649  30.9038 0019837 126.9344   3.6737 13.52683749559421')
}

Assuming that your content is in file.txt you can use the following. It shall work for any number of CALSPHERE keyword occurrences and also various number of entries between.

with open('file.txt') as inp:
    buffer = []
    for line in inp: 
        # remove newline
        copy = line.replace('\n','')
        # check if next entry
        if 'CALSPHERE' in copy:
            buffer.append([]) 
        # add line
        buffer[-1].append(copy)
    # put the output into dictionary
    res = {}
    for chunk in buffer:  
        # safety check
        if len(chunk) > 1:
            res[chunk[0]] = tuple( chunk[1:] ) 
    print(res)
Related