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 text file into dictionary with multiple keys in python

i have order.txt file

order_no:0
customer_name:John
customer_address:Unit 2, 12 Main Street, LONDON, WH1 2ER
customer_phone:0789887334
courier:2
status:preparing
####
order_no:1
customer_name:Adam
customer_address:Unit 3, 13 Main Street, LONDON, WH1 2ER
customer_phone:0799887334
courier:3
status:preparing

I would like to use python to read my file and using a dictionary and lists to populate the output as below.

[{"order_no":0, "customer_name": "John","customer_address": "Unit 2, 12 Main Street, LONDON, WH1 2ER",
"customer_phone": "0789887334","courier": 2,"status": "preparing"},{"order_no":1, "customer_name": "Adam","customer_address": "Unit 3, 12 Main Street, LONDON, WH1 2ER",
"customer_phone": "0799887334","courier": 3,"status": "preparing"}]

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

>Solution :

You want to itterate through the lines and split them on :,
Once you find # you will want to add the dict to a output list
something like this should work

with open("order.txt", "r") as f:
    res = []
    start = dict()
    for line in f:
        line = line.strip()
        if line[0] == '#':
            res.append(start)
            start = dict()
        else:
            add = line.split(":")
            start[add[0]] = add[1]
    res.append(start)

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