首页 > 解决方案 > 修改 geojson 在命令行上工作,但从脚本:Python NoneType object is not subscriptable

问题描述

我正在尝试修改 geojson 文件中元素的属性。使用命令行非常容易。

>>>import json
>>>with open(file_line) as f:
   ...     data = json.load(f)
>>>constituency_feature = next((item for item in data['features'] if item['properties']['name_4'] == 'Ahlaf'), None)
>>>constituency_feature['properties']['results'] = 'Winner'

确实,我得到:

constituency_feature['properties']['results']
'Winner'

但是当我尝试在我的 python 文件中执行此操作时,出现错误:

import json
import numpy as np

file_line = 'C:/Users/XXX/Documents/Programming/electoral-prediction-model-pk/data/Country/country-swing.json'

with open(file_line) as f:
    data = json.load(f)
for constituency in constituencies:      
    # predict
    # aquí queremos poner los resultados en el archivo Geojson que coincide con los nombres de los distritos electorales
    winning_party = "Test_party"
    # update geojson
    constituency_feature = next((item for item in data['features'] if item['properties']['name_4'] == constituency), None)
    print(constituency_feature)
    constituency_feature['properties']['results'] = winning_party_name

确实,我得到:

Traceback (most recent call last):
  File "C:/Users/antoi/Documents/Programming/electoral-prediction-model-pk/main.py", line 43, in <module>
    final_model(paras[:12])
  File "C:\Users\antoi\Documents\Programming\electoral-prediction-model-pk\model.py", line 105, in final_model
    constituency_feature['properties']['results'] = winning_party_name
TypeError: 'NoneType' object is not subscriptable

我查了一下,constituency_feature没有。

数据

例如,使用circunscripcion.geojson

{
  "type": "FeatureCollection",
  "totalFeatures": 1515,
  "features": [
    {
      "type": "Feature",
      "id": "fd597jf1799.1",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [
                -7.27163887,
                33.24041367
              ],
              [
                -7.27286911,
                33.24623871
              ],
              [
                -7.26732922,
                33.25904083
              ]
            ]
          ]
        ]
      },
      "geometry_name": "geom",
      "properties": {
        "id_0": 152,
        "iso": "MAR",
        "name_0": "Morocco",
        "id_1": 1,
        "name_1": "Chaouia - Ouardigha",
        "id_2": 1,
        "name_2": "Ben Slimane",
        "id_3": 1,
        "name_3": "Ben Slimane",
        "id_4": 1,
        "name_4": "Ahlaf",
        "varname_4": null,
        "ccn_4": 0,
        "cca_4": null,
        "type_4": "Commune Rural",
        "engtype_4": "Rural Commune",
        "bbox": [
          -7.27286911,
          33.22112656,
          -6.93353081,
          33.38970184
        ],
        "swing_count": 1,
        "polling_station_count": 15,
        "turnout": 0.4780299144225693,
        "results": {
          "PI": 187,
          "PJD": 88,
          "PAM": 59,
          "USFP": 1530,
        },
        "voter_file": {
          "nbre_sieges": 3,
          "nbre_inscrits": 5953,
          "nbre_votants": 2997,
          "nbre_nuls": 328,
          "nbre_exprimees": 2669
        },
        "swing_ratio": 0.06666666666666667
      }
    },
    {
      "type": "Feature",
      "id": "fd597jf1799.2",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [
                -7.00001287,
                33.63414383
              ],
              [
                -7.00081205,
                33.6269989
              ],
              [
                -6.99825382,
                33.60465622
              ]
            ]
          ]
        ]
      },
      "geometry_name": "geom",
      "properties": {
        "id_0": 152,
        "iso": "MAR",
        "name_0": "Morocco",
        "id_1": 1,
        "name_1": "Chaouia - Ouardigha",
        "id_2": 1,
        "name_2": "Ben Slimane",
        "id_3": 1,
        "name_3": "Ben Slimane",
        "id_4": 2,
        "name_4": "Ain Tizgha",
        "varname_4": null,
        "ccn_4": 0,
        "cca_4": null,
        "type_4": "Commune Rural",
        "engtype_4": "Rural Commune",
        "bbox": [
          -7.12737417,
          33.57954407,
          -6.99144888,
          33.78071213
        ],
        "swing_count": 11,
        "polling_station_count": 23,
        "turnout": 0.3912592182242994,
        "results": {
          "PI": 1837,
          "PJD": 366,
          "PAM": 143,
          "USFP": 22,
        },
        "voter_file": {
          "nbre_sieges": 3,
          "nbre_inscrits": 8262,
          "nbre_votants": 4479,
          "nbre_nuls": 443,
          "nbre_exprimees": 4036
        },
        "swing_ratio": 0.4782608695652174
      }
    }
  ],
  "crs": {
    "type": "name",
    "properties": {
      "name": "urn:ogc:def:crs:EPSG::4326"
    }
  },
  "bbox": [
    -13.2287693,
    27.62881088,
    -0.93655348,
    35.96390533
  ]
}

例如,假设我们正在处理Ahlaf: winning_party= PAM。如何摆脱“结果”字典并将“获胜者”:“PAM”放在适当的位置?这是预期的结果:

{
  "type": "FeatureCollection",
  "totalFeatures": 1515,
  "features": [
    {
      "type": "Feature",
      "id": "fd597jf1799.1",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [
                -7.27163887,
                33.24041367
              ],
              [
                -7.27286911,
                33.24623871
              ],
              [
                -7.26732922,
                33.25904083
              ]
            ]
          ]
        ]
      },
      "geometry_name": "geom",
      "properties": {
        "id_0": 152,
        "iso": "MAR",
        "name_0": "Morocco",
        "id_1": 1,
        "name_1": "Chaouia - Ouardigha",
        "id_2": 1,
        "name_2": "Ben Slimane",
        "id_3": 1,
        "name_3": "Ben Slimane",
        "id_4": 1,
        "name_4": "Ahlaf",
        "varname_4": null,
        "ccn_4": 0,
        "cca_4": null,
        "type_4": "Commune Rural",
        "engtype_4": "Rural Commune",
        "bbox": [
          -7.27286911,
          33.22112656,
          -6.93353081,
          33.38970184
        ],
        "swing_count": 1,
        "polling_station_count": 15,
        "turnout": 0.4780299144225693,
        "winning_party": "PAM",
        "voter_file": {
          "nbre_sieges": 3,
          "nbre_inscrits": 5953,
          "nbre_votants": 2997,
          "nbre_nuls": 328,
          "nbre_exprimees": 2669
        },
        "swing_ratio": 0.06666666666666667
      }
    },
    {
      "type": "Feature",
      "id": "fd597jf1799.2",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [
                -7.00001287,
                33.63414383
              ],
              [
                -7.00081205,
                33.6269989
              ],
              [
                -6.99825382,
                33.60465622
              ]
            ]
          ]
        ]
      },
      "geometry_name": "geom",
      "properties": {
        "id_0": 152,
        "iso": "MAR",
        "name_0": "Morocco",
        "id_1": 1,
        "name_1": "Chaouia - Ouardigha",
        "id_2": 1,
        "name_2": "Ben Slimane",
        "id_3": 1,
        "name_3": "Ben Slimane",
        "id_4": 2,
        "name_4": "Ain Tizgha",
        "varname_4": null,
        "ccn_4": 0,
        "cca_4": null,
        "type_4": "Commune Rural",
        "engtype_4": "Rural Commune",
        "bbox": [
          -7.12737417,
          33.57954407,
          -6.99144888,
          33.78071213
        ],
        "swing_count": 11,
        "polling_station_count": 23,
        "turnout": 0.3912592182242994,
        "results": {
          "PI": 1837,
          "PJD": 366,
          "PAM": 143,
          "USFP": 22
        },
        "voter_file": {
          "nbre_sieges": 3,
          "nbre_inscrits": 8262,
          "nbre_votants": 4479,
          "nbre_nuls": 443,
          "nbre_exprimees": 4036
        },
        "swing_ratio": 0.4782608695652174
      }
    }
  ],
  "crs": {
    "type": "name",
    "properties": {
      "name": "urn:ogc:def:crs:EPSG::4326"
    }
  },
  "bbox": [
    -13.2287693,
    27.62881088,
    -0.93655348,
    35.96390533
  ]
}

标签: python-3.xgeojson

解决方案


您可以通过以下方式访问'name_4'

print(data['features'][0]['properties']['name_4'])

您可以通过以下方式访问'results'

print(data['features'][0]['properties']['name_4'])

所以,一旦你有了正确的条件,你可以改变你需要的任何东西:

data['features'][0]['properties']['winner']='PAM'   # adds key 'winner' with value 'PAM'
del(data['features'][0]['properties']['results'])   # delete key 'results'

print(json.dumps(data, indent=2))                   # print (test) result

字典基本上是无序的,因此新键可能出现在['properties']字典中的不同位置。Python 3.6 或更高版本使用添加项目的顺序,因此对于这些版本,新项目['winner']将作为['properties']字典的最后一项添加


推荐阅读