簡體   English   中英

將 json 轉換為 python 中累積數據的字典

[英]Convert json into dictionary in python accumulating over data

給定一個 json 文件 data.json,我想通過使用三個不同的函數將我存儲在變量 data_list 中的 json 文件減少到三個不同的字典犯罪、犯罪 1 和犯罪 2

    [{"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_crimeMurderAssaultnon_violentTheft和車輛Vehicle_theft

我通過使用 function 來制作所有三個字典

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

這里是 go:

from collections import defaultdict
import json

murder_by_region = defaultdict(int)
violent_per_region = defaultdict(int)
nonviolent_per_region = defaultdict(int)

with open('/content/data_crime.json') as f:
    data_list = json.load(f)
    for row in data_list:
        region = row['Region']
        murder_by_region[region] += int(row.get('Murder', 0))
        violent_per_region[region] += int(row.get('Murder', 0)) + int(row.get('Assault', 0))
        nonviolent_per_region[region] += int(row.get('Theft', 0)) + int(row.get('Vehicle_Theft', 0))

為什么不把它做成一個字典字典,其中的鍵是城市名稱,

然后這樣做,它可以很容易地調整以獲得像你一樣的輸入。

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']
        }

暫無
暫無

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

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