You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python中构建嵌套字典并将其写入JSON文件?

How to Nest Dictionaries in Python & Write Valid JSON

Hey there! Let's work through your problem step by step—first, we'll fix a small issue with your intended JSON structure, then walk through nesting dictionaries and writing the result to a file.

First, Fix the JSON Structure (Critical!)

Your example structure has a small problem: JSON objects (Python dictionaries) require every entry to be a "key": value pair. You can't have anonymous sub-dictionaries floating directly inside the main dictionary. Here's the corrected, valid structure we'll aim for:

{
    "Action": null,
    "Parameter": "abc",
    "ParameterDescription": "def",
    "ExpectedValue": "ghi",
    "ExtensionsSection": {
        "Extensions":"jkl",
        "MappedData": "no",
        "Parameters": "pqr",
        "Labels": "Stu"
    },
    "RecorderSection": {
        "Recorder": "abc",
        "Diagnostics": "efg",
        "AdditionalRemarks": ""
    }
}

Each sub-dictionary gets a unique key (like "ExtensionsSection") so the JSON remains valid and parsable.

Step 1: Define Dictionaries in Separate Files

First, set up your external dictionary files. For example:

  • Create extension_data.py:
# extension_data.py
extensions_dict = {
    "Extensions":"jkl",
    "MappedData": "no",
    "Parameters": "pqr",
    "Labels": "Stu"
}
  • Create recorder_data.py:
# recorder_data.py
recorder_dict = {
    "Recorder": "abc",
    "Diagnostics": "efg",
    "AdditionalRemarks": ""
}

Step 2: Import & Nest Dictionaries in demo.py

In demo.py, import your external dictionaries and add them as nested entries to your temp_dict:

# demo.py
import json
from extension_data import extensions_dict
from recorder_data import recorder_dict

# Initialize your main dictionary
temp_dict = {
    "Action": None,
    "Parameter": "abc",
    "ParameterDescription": "def",
    "ExpectedValue": "ghi"
}

# Add nested dictionaries to temp_dict
temp_dict["ExtensionsSection"] = extensions_dict
temp_dict["RecorderSection"] = recorder_dict

This directly assigns each external dictionary to a new key in temp_dict, creating the nested structure you need.

Step 3: Optimize the write_json Function

Your original function works, but we can tweak it to produce human-readable JSON and handle encoding properly:

def write_json(new_data, filename='report.json'):
    # Use indent for readability, ensure UTF-8 encoding
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(new_data, f, indent=4, ensure_ascii=False)

Then call the function in demo.py to save your nested dictionary:

# Write the final nested structure to JSON
write_json(temp_dict)

Quick Notes

  • Validity first: Always stick to key-value pairs in JSON—anonymous entries will break parsers.
  • File paths: Make sure your external dictionary files are in the same folder as demo.py, or add their directory to Python's sys.path if they're elsewhere.
  • Appending instead of overwriting: If you need to add data to an existing JSON file (not replace it), you'd first read the existing content, update it, then write it back. Just let me know if you need help with that!

内容的提问来源于stack exchange,提问作者prithvi

火山引擎 最新活动