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