python - 将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_region
、violent_by_region
和
nonviolent_by_region
.
data_list
创建字典使用累积模式
迭代创建字典violent_crime
is Murder
andAssault
和non_violent
is Theft
andVehicle_theft
我通过使用制作所有三个字典的功能来做到这一点
function takes three parameters:
Key: region or state
crime : 'Murder'
data_list:the list containing dictionaries for each city
解决方案
为什么不把它做成一个字典字典,其中的键是城市名称,
然后这样做,它可以很容易地调整以获得像你一样的输入。
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']
}
推荐阅读
- outlook - How to update existing office addin?
- php - Wordpress DB 选择总是返回空
- php - Laravel 会话超时,额外的注销代码
- php - DRUPAL 8 - ajax 回调后无法更新单选按钮字段
- python - OpenCV(3.4.2): error: (-215:Assertion failed) with Template Matching Method
- google-cloud-storage - 有没有办法将 TSV 文件从存储桶转储到 GCP 中的 Cloud MySql?
- php - 在服务器上出现错误并在本地主机上正常工作,Laravel CTE(邻接)
- objective-c - 从swift调用objc类符合的私有协议方法
- sql - 了解 SQL 中主键值在表中重复的主键?
- wordpress - 返回用户元键的值并将值更改为数字