Python 如何从复杂的字典中选择某个值
因此,我尝试使用shapely从地图上的某些位置获取州代码。 我找到了一种检查位置/坐标处于哪个状态的方法,但是我只想打印缩写的状态代码,而不是整个字典/功能 我的代码如下所示:Python 如何从复杂的字典中选择某个值,python,Python,因此,我尝试使用shapely从地图上的某些位置获取州代码。 我找到了一种检查位置/坐标处于哪个状态的方法,但是我只想打印缩写的状态代码,而不是整个字典/功能 我的代码如下所示: point = Point(-90, 38.62) for state in data['features']: polygon = shape(state['geometry']) if polygon.contains(point): print ('Found containin
point = Point(-90, 38.62)
for state in data['features']:
polygon = shape(state['geometry'])
if polygon.contains(point):
print ('Found containing polygon:', state)
它打印了这个:
Found containing polygon: {'type': 'Feature', 'properties': {'STATE_NAME': 'Illinois', 'DRAWSEQ': 27, 'STATE_FIPS': '17', 'SUB_REGION': 'East North Central', 'STATE_ABBR': 'IL'}, 'geometry': {'type': 'Polygon', 'coordinates': [[[-88.07159127841085, 37.51103836239962], [-88.08791027842605, 37.47632136236729], [-88.3117422786345, 37.44290336233617], [-88.35921427867872, 37.40936136230492], [-88.41989327873523, 37.42034336231515], [-88.46768627877974, 37.40080836229696], [-88.51136527882042, 37.29690536220019], [-88.5014692788112, 37.25783636216381], ....................
我如何在我的输出中得到“IL”
我试过:
print ('Found containing polygon:', state.get('STATE_ABBR'))
但这给了我“没有”而不是“我”
提前谢谢
但这给了我“没有”而不是“我”
当然,您的state
dict没有state\u ABBR
键,它的三个键是type
、properties
和geometry
。如果您使用常规索引,您会得到更清晰的keyrerror
STATE_ABBR
是properties
子目录的一部分,因此您首先需要访问:
state['properties']['state_ABBR']
您需要访问字典中的正确键:
print('Found containing polygon:', state['properties']['STATE_ABBR'])