简体   繁体   中英

How to format a dictionary with a list of items in Python

I have a python dictionary that I want to look like this:

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

currently it looks like this

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

The list of items can be different and does not have a fixed amount of items, so I would also need to to know how to do that

I have tried to add new lines in the dictionaries but it would not work and it would just put '\n' in to my dictionary

If you're trying to json.dump() it into a JSON file, using the json.dump() function you could pass in the indent argument for indentation (appears to be what you want) You can read more about it here
An example:

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

All this does is add indentation to the file to make it easier to read

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