简体   繁体   English

将文本文件转换为具有多个键的字典 python

[英]Convert text file into dictionary with multiple keys in python

i have order.txt file我有 order.txt 文件

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.我想使用 python 来读取我的文件并使用字典和列表来填充 output,如下所示。

[{"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你想遍历这些行并将它们拆分为:,一旦你找到#你会想要将字典添加到 output 列表中这样的事情应该有效

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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