Raj
Raj

Reputation: 55

python create json from loop

I am an python newbie trying to create data in json by iterating a for loop like {region1: title1, region2:title2}

Logic:

import json
for region in ["region1","region2","region3"]:
  title="logic to get the title in region"
  data = {region: title}
  # like to update_json.update(data) from second run

I would like the data to be appended with region:title for each loop run. Thanks in advance.

Upvotes: 0

Views: 85

Answers (1)

Justin Zhang
Justin Zhang

Reputation: 68

Use json.dumps(dict):

import json

dic = {}
for region in ["region1","region2","region3"]:
    title="logic to get the title in region"
    dic[region] = title
j = json.dumps(dic)  # here is

Upvotes: 1

Related Questions