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

如何用for循环遍历JSON对象并将每个值减1?

Subtract 1 from Each Value in a JSON Object

How It Works

When you use json.load(file), the JSON content gets parsed into a Python dictionary. To access both keys and their corresponding values during iteration, use the .items() method of the dictionary—it returns each key-value pair as a tuple.

Corrected Code

Here's the complete code to achieve your goal:

import json

# Safely read the JSON file using a with statement
with open('your_json_file.json', 'r') as file:
    json_data = json.load(file)

# Iterate over every key-value pair in the dictionary
for key, value in json_data.items():
    # Subtract 1 from the value and update the dictionary
    json_data[key] = value - 1

# Optional: Write the modified data back to a file (if needed)
with open('modified_json_file.json', 'w') as file:
    json.dump(json_data, file, indent=2)

Example Result

For your sample input JSON:

{
  "12345678910": 32,
  "10987654321": 21
}

After running the code, the modified data will be:

{
  "12345678910": 31,
  "10987654321": 20
}

Key Notes

  • Ensure all values in your JSON are numeric (integers or floats), otherwise subtracting 1 will throw an error.
  • The with statement automatically handles file closing, which is a recommended Python best practice.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 20:05:57