如何在python中循环字典并以JSON格式保存结果 - 格式无效

时间:2015-02-21 05:06:47

标签: python json dictionary

我循环遍历列表,然后循环Python中的字典,将数据存储在另一个字典中,并使用json.dump将数据写入json文件。我的JSON输出有点偏,有一些额外的括号和缺少注释。这是我的循环:

for zip_code in zip_codes:
  for key, code in census_codes.iteritems():
      stats[key] = c.acs.zipcode(('NAME', code), zip_code)[0][code]

  zip_stats = {}
  zip_stats[zip_code] = stats
  json.dump(zip_stats, ofile, indent=4) 

这是输出:

{
    "10001": {
        "total_population": "21097", 
        "widowed": "580", 
        "now_married": "4595", 
        "divorced": "4595", 
        "housing_units": "756", 
        "some_college": "2404", 
        "seperated": "346", 
        "hs_graduate": "1359", 
        "graduate": "4305", 
        "total_females": "11024", 
        "total_males": "10073", 
        "bachelors": "5705", 
        "average_age": "34.6", 
        "never_married": "11964"
    }
}{
    "10012": {
        "total_population": "28982", 
        "widowed": "1538", 
        "now_married": "14932", 
        "divorced": "14932", 
        "housing_units": "799", 
        "some_college": "2574", 
        "seperated": "136", 
        "hs_graduate": "2622", 
        "graduate": "6510", 
        "total_females": "14668", 
        "total_males": "14314", 
        "bachelors": "7275", 
        "average_age": "42.8", 
        "never_married": "4743"
    }
}

为什么json.dumps()没有将输出格式化为有效的JSON?

1 个答案:

答案 0 :(得分:0)

尝试:

zip_stats = {}
for zip_code in zip_codes:
    stats = {}
    for key, code in census_codes.iteritems():
        stats[key] = c.acs.zipcode(('NAME', code), zip_code)[0][code]
    zip_stats[zip_code] = stats
json.dump(zip_stats, ofile, indent=4) 

您的代码为每个zip_stats创建了一个新的zip_code字典,并将每个字典写为单独的JSON字符串。我创建了一次字典,添加了2个统计字典,并且仅dump一次。