如何用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
withstatement automatically handles file closing, which is a recommended Python best practice.
内容的提问来源于stack exchange,提问作者Mashhhyyy
相关产品推荐
相关产品推荐

