question 115 Collection Algorithms · medium
Parse raw invoice lines
An export arrives as plain text lines, one invoice line each, with fields separated by commas: invoice, stock code, description, quantity, price, customer ID. Turn every line into a dictionary with proper types so the rest of the pipeline can do arithmetic on it.
Function
parse_lines(lines)linesa list of texts like
"489438,21329,DINOSAURS WRITING SET,28,0.98,18102" (descriptions never contain commas)Returnsa new list with one dictionary per line:
invoice (text), stock_code (text), description, quantity (int), price (float), customer_iddescriptionspaces at the ends removed and each double space replaced by one space
customer_idthe text, or
None when that field is empty (anonymous orders)Examples
callparse_lines(['489438,21329,DINOSAURS WRITING SET,28,0.98,18102'])returns[{'invoice': '489438', 'stock_code': '21329', 'description': 'DINOSAURS WRITING SET', 'quantity': 28, 'price': 0.98, 'customer_id': '18102'}]
callparse_lines(['489438,21252,SET OF MEADOW FLOWER STICKERS,30,1.69,18102', '489438,20711,JUMBO BAG TOYS,60,1.3,18102'])returns[{'invoice': '489438', 'stock_code': '21252', 'description': 'SET OF MEADOW FLOWER STICKERS', 'quantity': 30, 'price': 1.69, 'customer_id': '18102'}, {'invoice': '489438', 'stock_code': '20711', 'description': 'JUMBO BAG TOYS', 'quantity': 60, 'price': 1.3, 'customer_id': '18102'}]
callparse_lines([])returns[]