Python从URL嵌套JSON生成合并格式字典的问题求解
如何将循环生成的键值对合并为单个
new_context字典? 你现在的问题是从URL获取嵌套JSON后,循环输出的是多个独立的new_context字典,但希望把所有键值对整合到同一个new_context里对吧?
原代码及问题
你的原代码是这样的:
import json import urllib.request data = urllib.request.urlopen("https://url").read() output = json.loads(data) for each in output['toplevel']: Key = each['Key'] Value = each['Value'] string = {Key:Value} print(dict(new_context = string))
运行后返回的是多个独立的结果:
{'new_context': {'the_Key1': 'the_Value1'}} {'new_context': {'the_Key2': 'the_Value2'}} {'new_context': {'the_Key3': 'the_Value3'}}
而你期望的是一个包含所有键值对的字典:
{'new_context': {'the_Key1': 'the_Value1', 'the_Key2': 'the_Value2', 'the_Key3': 'the_Value3'}}
修改后的代码及解释
核心思路是先收集所有键值对到一个字典中,最后再统一输出,而不是每次循环都单独输出:
import json import urllib.request data = urllib.request.urlopen("https://url").read() output = json.loads(data) # 初始化空字典,用来存放所有键值对 combined_dict = {} for each in output['toplevel']: # 变量名改用小写,符合Python的PEP8规范 key = each['Key'] value = each['Value'] # 将当前键值对添加到合并字典中 combined_dict[key] = value # 循环结束后,一次性输出整合后的结果 print({'new_context': combined_dict})
为什么这样能解决问题?
- 原代码在每次循环中都会创建一个仅包含当前键值对的小字典
string,然后直接打印{'new_context': string},所以每次输出都是独立的条目。 - 修改后我们先把所有键值对逐步添加到
combined_dict里,等所有数据都收集完成后,再把这个完整的字典包裹到new_context中输出,自然就得到了你想要的合并格式。
内容的提问来源于stack exchange,提问作者mikswe
相关产品推荐
相关产品推荐

