簡體   English   中英

將文本文件轉換為具有多個鍵的字典 python

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

我有 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

我想使用 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"}]

你想遍歷這些行並將它們拆分為:,一旦你找到#你會想要將字典添加到 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