0

I have some data in the following variables,

want to store the python dictionary in the following JSON format,

{
  'name': {
  'Address': '123 abc, IN, 50012',
  'Phone': '123456',
  },
  'name2': {
  'Address': '123 abc, IN, 50012',
  'Phone': '123456',
  },
}

Updated JSON format(Required in this format)

{
  "name":[
  {"Address": "123 abc, IN, 50012"},
  {"Phone": "123456"}
  ],
  "name2": [
  {"Address": "123 abc, IN, 50012"},
  {"Phone": "123456"}
  ]
}

But I managed only to get the JSON in this format,

{"phone": "123456738", "address": "address1,", "name": "name1"}
{"phone": "123456178", "address": "address2,", "name": "name2"}
{"phone": "123452678", "address": "address3,", "name": "name3"}

below is my code

#getting data and adding to dict
dict_list = []
for data in all_data:
    dict = {}
    dict["phone"] = phone.strip()
    dict["address"] = address.strip()
    dict["name"] = name.strip()
    dict_list.append(dict)

#writing to json file
with open('data.json', 'w') as outfile:
  for details in dict_list:
    r = json.dumps(details)
    loaded_r = json.loads(r)
    json.dump(loaded_r, outfile)
Mann
  • 576
  • 1
  • 9
  • 33

1 Answers1

0

you want to convert the inner dictionary to a list of dictionaries containing only one key & value. Doable with some comprehension syntax:

in_dict = {
  'name': {
  'Address': '123 abc, IN, 50012',
  'Phone': '123456',
  },
  'name2': {
  'Address': '123 abc, IN, 50012',
  'Phone': '123456',
  },
}

out_dict = {k : [{k2:v2} for k2,v2 in v.items()] for k,v in in_dict.items()}

For each key,value (dictionary) pair, iterate on items of the sub-dict and create 1 dictionary per key,value in a list.

result:

>>> out_dict
{'name': [{'Address': '123 abc, IN, 50012'}, {'Phone': '123456'}],
 'name2': [{'Address': '123 abc, IN, 50012'}, {'Phone': '123456'}]}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219