以JSON格式保存Python字典

时间:2019-02-18 09:33:58

标签: json python-3.x dictionary

我在以下变量中有一些数据,

想要以以下JSON格式存储python字典,

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

更新的JSON格式(此格式必需)

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

但是我只能以这种格式获取JSON,

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

下面是我的代码

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

1 个答案:

答案 0 :(得分:0)

您想将内部词典转换为仅包含一个键和值的词典列表。可以使用一些理解语法:

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

对于每个键/值(字典)对,迭代子字典的项,并为每个键/值在list中创建1个字典。

结果:

>>> out_dict
{'name': [{'Address': '123 abc, IN, 50012'}, {'Phone': '123456'}],
 'name2': [{'Address': '123 abc, IN, 50012'}, {'Phone': '123456'}]}