如何将Python列表元素映射到JSON结构的number和result字段?
Your initial update() approach wasn't hitting the right spot—it was adding top-level keys to finaldata instead of targeting the nested origination array inside type[0]. Here's how to correctly fill that array, even when your list length changes:
Step-by-Step Implementation
First, define your input list and base data structure (I cleaned up the initial origination array to be empty since we'll generate it dynamically):
List4 = ['4','6','9','10'] # Works for any list length finaldata = { "animal":"cat", "type":[ { "weight":"true", "origination":[] } ] }
Next, generate the origination entries dynamically. We'll use enumerate() with a start value of 1 to get the 1-based index for the number field:
# Build the origination list with 1-based indices origination_entries = [] for position, item in enumerate(List4, start=1): origination_entries.append({ "number": str(position), "result": item }) # Replace the nested origination array in finaldata finaldata["type"][0]["origination"] = origination_entries
Finally, write the updated data to data.json using Python's built-in json module:
import json # Write to file with indentation for readability with open("data.json", "w") as output_file: json.dump(finaldata, output_file, indent=4)
Key Details
- Dynamic Entry Creation:
enumerate(List4, start=1)gives us each element plus its 1-based position (no manual index counting needed!). We convert the position to a string to match the expectednumberfield format. - Targeted Nested Update: Instead of modifying the top-level
finaldata, we directly accessfinaldata["type"][0]["origination"]to replace the array. This works whether your list is shorter or longer than the original 4 entries. - Clean JSON Output: The
indent=4argument makes the resulting JSON file easy to read.
Example Output for Your List4
Your data.json will look like this:
{ "animal": "cat", "type": [ { "weight": "true", "origination": [ { "number": "1", "result": "4" }, { "number": "2", "result": "6" }, { "number": "3", "result": "9" }, { "number": "4", "result": "10" } ] } ] }
If you extend List4 (e.g., add '12'), the origination array will automatically grow to include a 5th entry with number: "5" and result: "12".
内容的提问来源于stack exchange,提问作者user10737394

