Home > database >  Convert every 3 rows from a file into a key value array
Convert every 3 rows from a file into a key value array

Time:01-03

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:

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']

CodePudding user response:

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())

CodePudding user response:

Not sure if the values in your output array are strings or dictionaries, but here's one way to achieve what you're looking for:

def build_list():
    with open('invoice.txt', 'r') as file:
        info = [l.strip() for l in file.readlines()]
    for idx, line in enumerate(info):
        if idx % 3 == 0:
            yield [f'workorder: {info[idx]}', f'invoicenum: {info[idx   1]}', f'compdate: {info[idx   2]}']


list(build_list())

CodePudding user response:

With short iterator approach:

def build_list():
    keys = ['workorder', 'invoicenum', 'compdate']
    info = []
    with open('invoice.txt') as f:
        for line in f:
            info.append(dict(zip(keys, map(str.strip, [line, next(f), next(f)]))))
    return info

print(build_list())

[{'workorder': '123', 'invoicenum': '123', 'compdate': '01/01/2023'}, {'workorder': '1234', 'invoicenum': '1234', 'compdate': '01/01/2023'}, {'workorder': '12345', 'invoicenum': '12345', 'compdate': '01/01/2023'}]
  • Related