Python如何通过for循环迭代生成指定键值对结构的JSON数据
实现方法
你只需要在循环外先初始化一个空字典用来累积所有键值对,每次循环直接往这个字典里追加键值对即可,不用区分是否是第一次循环,空字典也支持直接添加新键值对。
完整修改后代码
import json # 循环外初始化空字典存储最终数据 update_json = {} for region in ["region1","region2","region3"]: title = "logic to get the title in region" # 两种写法选一种即可 # 写法1:直接赋值添加键值对,更简洁 update_json[region] = title # 写法2:用你提到的update方法,效果完全一致 # update_json.update({region: title}) # 转成标准JSON格式字符串 final_json = json.dumps(update_json, ensure_ascii=False) # 打印验证结果 print(final_json)
运行后输出的结果就是你需要的结构:{"region1": "logic to get the title in region", "region2": "logic to get the title in region", "region3": "logic to get the title in region"}
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

