1

If you have a multilevel, nested json from url:

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))

This return:

{'new_context': {'the_Key1': 'the_Value1'}}
{'new_context': {'the_Key2': 'the_Value2'}}
{'new_context': {'the_Key3': 'the_Value3'}}

What i want:

{'new_context': {'the_Key1': 'the_Value1', 'the_Key2': 'the_Value2', 'the_Key3': 'the_Value3'}}
1
  • 2
    just look up how to a) create an empty dictionary, b) add elements to it. Right now you are making new dictionaries in each loop. Commented Nov 8, 2019 at 22:08

2 Answers 2

2

Here you go :

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)

Sign up to request clarification or add additional context in comments.

Comments

1
d={}
keys=['1','2','3']
vals=['one','two', 'three']

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

print(d)

output:

{'1': 'one', '2': 'two', '3': 'three'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.