简体   繁体   中英

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"}]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM