繁体   English   中英

如何用 Python 中的项目列表格式化字典

[英]How to format a dictionary with a list of items in Python

我有一本 python 字典,我希望它看起来像这样:

{"name": "BOB", 
    "item1": {
        "item name": "bread",
        "quantity of item ": 10,
        "price of item": "3.00"
    }, 
    "item2": {
        "item name": "milk",
        "quantity of item ": 15,
        "price of item": "9.00"
    }
}

目前看起来像这样

{"name": "BOB", "item1": {"item name": "bread", "quantity of item ": 10, "price of item": "3.00"}, "item2": {"item name": "milk", "quantity of item ": 15, "price of item": "9.00"}}

项目列表可以不同并且没有固定数量的项目,所以我还需要知道该怎么做

我试图在字典中添加新行,但它不起作用,它只会将 '\n' 放入我的字典中

如果您尝试使用json.dump()将它放入 JSON 文件中,使用json.dump() function 您可以传入用于缩进的indent参数(似乎是您想要的)您可以在此处阅读更多相关信息
一个例子:

json.dump(jsonData, jsonFile, indent=2) # indentation is usually in spaces, so 2 would mean 2 spaces indentation, but you can replace it with '\t' for tabs

所有这一切都是在文件中添加缩进以使其更易于阅读

暂无
暂无

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

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