python - 我如何解析具有相同多个键的json:python中的值对,稍后我需要求和
问题描述
我需要解析与下面的示例相同的 JSON 文件。我需要将每个属性值与其他属性值相加,以将每个人都聚集在一起,就像p_30_34_yrs
与其他属性一样p_30_34_yrs
等等。我需要 JSON 文件作为带有这些附加值的结果p_30_34_yrs
- 一起,p_tot 一起等等。请帮助我,因为我对 Python 很陌生。我能够解析它load()
并给我dict
,但是当我喜欢dict["features"]
它时,它会将它转换为list
甚至在list
我无法获取我应用的每个属性键值sum()
。
Example:
{
"type":"..",
"box":[..],
"crs":{
..
},
"features":[
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [..]
},
"properties": {
"p_30_34_yrs": 421,
"p_tot": 3210,
"year": "2014",
"p_75_79_yrs": 30,
"p_40_44_yrs": 259,
"p_55_59_yrs": 174,
"p_65_69_yrs": 96
},
"id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb1"
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
..
]
},
"properties": {
"p_30_34_yrs": 2316,
"p_tot": 22690,
"year": "2014",
"p_75_79_yrs": 461,
"p_40_44_yrs": 1211,
"p_55_59_yrs": 1031,
"p_65_69_yrs": 1071
},
"id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb0"
},
and same way 6 more times.
]
}
解决方案
像这样的东西(测试代码)?
jsn = {
"type": "..",
"box": "[..]",
"features": [{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": "[..]"
},
"properties": {
"p_30_34_yrs": 421,
"p_tot": 3210,
"year": "2014",
"p_75_79_yrs": 30,
"p_40_44_yrs": 259,
"p_55_59_yrs": 174,
"p_65_69_yrs": 96
},
"id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb1"
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"p_30_34_yrs": 2316,
"p_tot": 22690,
"year": "2014",
"p_75_79_yrs": 461,
"p_40_44_yrs": 1211,
"p_55_59_yrs": 1031,
"p_65_69_yrs": 1071
},
"id": "lga_nrp_people_2010_2014.fid--2ea3ac96_1631a637772_-4cb0"
}
]
}
data = jsn["features"]
props = {"p_30_34_yrs": 0,
"p_tot": 0,
"p_75_79_yrs": 0,
"p_40_44_yrs": 0,
"p_55_59_yrs": 0,
"p_65_69_yrs": 0}
for feat in data:
if "properties" in feat:
if "p_30_34_yrs" in feat["properties"]: props["p_30_34_yrs"] += feat["properties"]["p_30_34_yrs"]
if "p_tot" in feat["properties"]: props["p_tot"] += feat["properties"]["p_tot"]
if "p_75_79_yrs" in feat["properties"]: props["p_75_79_yrs"] += feat["properties"]["p_75_79_yrs"]
if "p_40_44_yrs" in feat["properties"]: props["p_40_44_yrs"] += feat["properties"]["p_40_44_yrs"]
if "p_55_59_yrs" in feat["properties"]: props["p_55_59_yrs"] += feat["properties"]["p_55_59_yrs"]
if "p_65_69_yrs" in feat["properties"]: props["p_65_69_yrs"] += feat["properties"]["p_65_69_yrs"]
print(props)
推荐阅读
- amazon-web-services - .StartExecution 不是函数
- r - R ggplot geom_col 绘制一个变量的比例
- sql - 从所有组中返回 1 行
- matlab - 在 Octave 中调用向量化操作以获得多个输出
- javascript - 如何在VSCODE中将反斜杠更改为前斜杠?
- javascript - pm2 文件夹路径和多个运行脚本
- julia - 朱莉娅有克罗内克三角洲吗?
- python - 如何在随机选择函数中读取包含两列的行文件
- apache-nifi - 如何在 nifi 中为 csv 文件生成 Avro 模式
- powershell - PowerShell Studio exe不会在打包的exe中按下按钮时启动新的Windows窗体