Python社区  »  Python

在Python中从json创建新数组

mikswe • 1 周前 • 14 次点击  

如果url中有多级嵌套json:

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'}}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49297
 
14 次点击  
分享到微博
文章 [ 2 ]  |  最新文章 1 周前
roadrunner66
Reply   •   1 楼
roadrunner66    1 周前
d={}
keys=['1','2','3']
vals=['one','two', 'three']

for i in range(3):
    d[keys[i]]=vals[i]

print(d)

输出:

{'1': 'one', '2': 'two', '3': 'three'}
WaspCo
Reply   •   2 楼
WaspCo    1 周前

干得好:

import json
import urllib.request

data = urllib.request.urlopen("https://url").read()
output = json.loads(data)

result = {"new_context": {}}

for each in output['toplevel']:

    result["new_context"][each['Key']] = each['Value']

print(result)