簡體   English   中英

如何在python中循環字典並以JSON格式保存結果 - 格式無效

[英]How to Loop through a dictionary in python and save results in JSON format - invalid format

我循環遍歷列表,然后循環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?

嘗試:

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_code創建了一個新的zip_stats字典,並將每個字典寫為單獨的JSON字符串。 我創建一次字典,添加2個統計字典,並且只dump一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM