Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert every 3 rows from a file into a key value array

I have a text file with multiple lines. How can I assign each row to the key in multiples of 3?

Text file:

123
123
01/01/2023
1234
1234
01/01/2023
12345
12345
01/01/2023

Python:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def build_list():
    key = ['workorder', 'invoicenum', 'compdate']
    with open('invoice.txt', 'r') as file:
        info = file.read().rstrip('\n')

    return info

Output should look like this:

['workorder: 123', 'invoicenum': 123, 'compdate': '01/01/2023'],
['workorder: 1234', 'invoicenum': 1234, 'compdate': '01/01/2023'],
['workorder: 12345', 'invoicenum': 12345, 'compdate': '01/01/2023']

>Solution :

Use zip() to group the lines in multiples of 3 and Use zip() to group the lines in multiples of 3.

def build_list():
    key = ['workorder', 'invoicenum', 'compdate']
    with open('invoice.txt', 'r') as file:
        lines = file.readlines()

    # Group the lines in multiples of 3
    groups = zip(*[iter(lines)]*3)

    # Build the list of dictionaries
    result = []
    for group in groups:
        result.append({k:v for k, v in zip(key, group)})

    return result

if you want to remove \n at the end of each lines, you should write like this:

def build_list():
    key = ['workorder', 'invoicenum', 'compdate']
    with open('invoice.txt', 'r') as file:
        lines = file.read().rstrip('\n').split('\n')

    values = []
    for i in range(0, len(lines), 3):
        # Get the current chunk of lines
        chunk = lines[i:i+3]
        chunk = [value.strip() for value in chunk]
        values.append(dict(zip(key, chunk)))
    return values

print(build_list())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading