You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python更新并添加JSON文件中字典的键值对

Solution to Update and Add Key-Value Pairs in JSON File

Hey there! Let's get your JSON file updated exactly how you want it. You've already nailed the initial steps—loading the JSON data and defining the key-value pairs you need. Here's how to wrap it up perfectly:

Step-by-Step Breakdown

  • Add site_id to the site_post section: We'll directly insert the new key-value pair here using the value from your dct variable.
  • Update plant_post with new values: Use Python's built-in dictionary update() method to replace the empty site_id and plant_id entries with your desired values.
  • Write changes back to the file: Save the modified data with proper indentation to keep the JSON structure clean and readable.

Complete Working Code

import json

# Load the existing JSON data from hi.json
with open('hi.json') as f:
    data = json.load(f)

# Define the key-value pairs we need to update/add
dct = {"site_id":"123","plant_id":"456"}

# Add site_id to the site_post dictionary
data['site_post']['site_id'] = dct['site_id']

# Update plant_post with both key-value pairs from dct
data['plant_post'].update(dct)

# Write the modified data back to hi.json (with indentation for readability)
with open('hi.json', 'w') as f:
    json.dump(data, f, indent=2)

What Each Part Does

  • data['site_post']['site_id'] = dct['site_id']: This line directly adds the site_id key to the site_post section, setting its value to "123" as specified.
  • data['plant_post'].update(dct): The update() method merges your dct into the plant_post dictionary, automatically overwriting the empty site_id and plant_id values with your new ones.
  • json.dump(data, f, indent=2): Writes the updated data back to the file, and the indent=2 parameter ensures the JSON stays formatted neatly just like your expected output.

After running this code, your hi.json will match exactly the result you shared!

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:22:32