Split then strip txt lines then save to dictionary

Question:

I have this .txt file that I wanted to split, strip then save the content to a dictionary

Jon, ID1, 30.0, ID2, 35.4, ID3, 478.5
Paige, ID1, 15.8, ID3, 723.5, ID4, 250, ID6, 66.2
Jil, ID1, 46.2, ID2, 37.7, ID3, 68.4, ID4, 40, ID5, 22
Jig5, ID1, 90.5, ID2, 69.4, ID6, 35.8
Kit4, ID3, 700.2, ID4, 260, ID5, 96

I wanted to achieve an output that is similar to this

Jon {ID1: 30.0, ID2: 35.4, ID3: 478.5}
Paige {ID1: 15.8, ID3: 723.5, ID4: 250, ID6: 66.2}
Jil {ID1: 46.2, ID2: 37.7, ID3: 68.4, ID4: 40, ID5: 22}
Jig5 {ID1: 90.5, ID2: 69.4, ID6: 35.8
Kit4 {ID3: 700.2, ID4: 260, ID5: 96}

I have tried:

output = {}

with open("records.txt", "r") as f_in:
    for line in f_in: names = line[0].strip()
        usage = usage[1::2].strip()

        if usage == "":
            continue

        ID, SCORE = usage.split(",")
        output[state] = capital

        print(output)
Asked By: Sheesh

||

Answers:

As a comment pointed out, your data is essentially a CSV file. Therefore, you can use the built-in csv module. Like this:

import csv


def pairs(lst):
    for i in range(0, len(lst), 2):
        yield (lst[i], lst[i + 1])


with open('test.csv', 'r') as f:
    for row in csv.reader(f):
        dct = {k.strip(): v.strip() for (k, v) in pairs(row[1:])}
        print(row[0], dct)

The first column is used as a header, while the rest is read in pairs by the helper generator function pairs() and put into a dictionary comprehension. I also used .strip() on the strings to remove the extra whitespace in your data.

Answered By: Michael M.
with open(r"records.txt") as f:
    data = {}
    for line in f:
        # Remove the trailing newline character
        line = line.rstrip()
        d = {}
        values = line.split(", ")
        name = values[0]
        
        # This returns a generator which yields the ids and numbers
        # The try-except block is used to keep the numbers the same 
        # as their string representation, e.g. "30.0" as 30.0, and 
        # "96" as 96 (instead of 96.0)
        for key, value in zip(values[1::2], values[2::2]):
            try:
                value = int(value)
            except ValueError:
                value = float(value)
                
            d[key] = value
        
        data[name] = d

with open(r"records (transformed).txt", "w") as f:
    for name, d in data.items():
        values = ", ".join(f"{key}: {value}" for key, value in d.items())
        f.write(f"{name} {{{values}}}n")

records.txt:

Jon, ID1, 30.0, ID2, 35.4, ID3, 478.5
Paige, ID1, 15.8, ID3, 723.5, ID4, 250, ID6, 66.2
Jil, ID1, 46.2, ID2, 37.7, ID3, 68.4, ID4, 40, ID5, 22
Jig5, ID1, 90.5, ID2, 69.4, ID6, 35.8
Kit4, ID3, 700.2, ID4, 260, ID5, 96

records (transformed).txt:

Jon {ID1: 30.0, ID2: 35.4, ID3: 478.5}
Paige {ID1: 15.8, ID3: 723.5, ID4: 250, ID6: 66.2}
Jil {ID1: 46.2, ID2: 37.7, ID3: 68.4, ID4: 40, ID5: 22}
Jig5 {ID1: 90.5, ID2: 69.4, ID6: 35.8}
Kit4 {ID3: 700.2, ID4: 260, ID5: 96}
Answered By: GordonAitchJay
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.