首页 > 解决方案 > 将json转换为python中累积数据的字典

问题描述

给定一个json文件data.json,我想通过使用三个不同的函数将存储在变量data_list中的json文件减少为三个不同的字典crime、crime1和crime2

    [{"Region": "South", "State": "ALABAMA", "City": "Athens", "Population": "25603", "Murder": "1", "Rape": "1", "Robbery": "16", "Assault": "0", "Burglary": "90", "Theft": "538", "Vehicle_Theft": "8"}, {"Region": "South", "State": "ALABAMA", "City": "Atmore", "Population": "10021", "Murder": "0", "Rape": "3", "Robbery": "14", "Assault": "76", "Burglary": "86", "Theft": "315", "Vehicle_Theft": "12"}]

我将它加载到一个变量中

    with open('/content/data_crime.json', 'r') as f:
          data_list = json.load(f)

我想将 data_list 减少为三个字典:murder_by_regionviolent_by_regionnonviolent_by_region.

data_list创建字典使用累积模式 迭代创建字典violent_crimeis MurderandAssaultnon_violentis TheftandVehicle_theft

我通过使用制作所有三个字典的功能来做到这一点

    function takes three parameters:
         
    Key: region or state
    crime : 'Murder' 
    data_list:the list containing dictionaries for each city

标签: pythondictionary

解决方案


为什么不把它做成一个字典字典,其中的键是城市名称,

然后这样做,它可以很容易地调整以获得像你一样的输入。

with open('data_crime.json', 'r') as File:
    FileData = json.load(File)
    ExitData = {} # empty dict
    nonViolent = ['Robbery', 'Burglary', 'etc..']
    Violent = ['Assult', 'Rape']
    for i in FileData:
        # i is the key or in this case the city name
        numOfNonViolent = 0
        for j in nonViolent:
            numOfNonViolent += FileData[i][j]
        numOfViolent = 0
        for j in Violent:
            numOfViolent += FileData[i][j]
        
        # will make a new key for ExitData the key is the city name
        ExitData[i] = {
            'Violent Crime' : numOfViolent
            'NonViolent Crime' : numOfNonViolent
            'Murder' : FileData[i]['Murder']
        }

推荐阅读