question 169 Nested Data Structures · hard
Follow a dotted path into a response
Monitoring rules are written as dotted paths, like "features.0.properties.mag", so non-programmers can point at a value inside a JSON response. Write the function that follows such a path. Each part is a dictionary key, or, when the current value is a list, a position written in digits.
Function
get_path(data, path, default=None)pathparts separated by dots, e.g.
"metadata.count" or "features.1.geometry.coordinates.2"Stepson a dictionary, the part must be one of its keys; on a list, the part must be all digits and a position inside the list; on anything else the path can't continue
Returnsthe value at the end of the path, or
default as soon as a step can't be takenRulesa value that exists but is
None is returned as None (it was found); isinstance(value, list) tells you a value is a listExamples
callget_path({'type': 'FeatureCollection', 'metadata': {'count': 2, 'status': 200}, 'features': [{'id': 'us6000pw8f', 'properties': {'mag': 4.6, 'felt': 1, 'alert': None}, 'geometry': {'coordinates': [122.5991, 8.8699, 10]}}, {'id': 'us6000pw8e', 'properties': {'mag': 4.4, 'felt': None}, 'geometry': {'coordinates': [-68.546, -21.7883, 123.298]}}]}, 'metadata.count')returns2
callget_path({'type': 'FeatureCollection', 'metadata': {'count': 2, 'status': 200}, 'features': [{'id': 'us6000pw8f', 'properties': {'mag': 4.6, 'felt': 1, 'alert': None}, 'geometry': {'coordinates': [122.5991, 8.8699, 10]}}, {'id': 'us6000pw8e', 'properties': {'mag': 4.4, 'felt': None}, 'geometry': {'coordinates': [-68.546, -21.7883, 123.298]}}]}, 'features.1.geometry.coordinates.2')returns123.298
callget_path({'type': 'FeatureCollection', 'metadata': {'count': 2, 'status': 200}, 'features': [{'id': 'us6000pw8f', 'properties': {'mag': 4.6, 'felt': 1, 'alert': None}, 'geometry': {'coordinates': [122.5991, 8.8699, 10]}}, {'id': 'us6000pw8e', 'properties': {'mag': 4.4, 'felt': None}, 'geometry': {'coordinates': [-68.546, -21.7883, 123.298]}}]}, 'features.5.id', 'missing')returns'missing'
callget_path({'type': 'FeatureCollection', 'metadata': {'count': 2, 'status': 200}, 'features': [{'id': 'us6000pw8f', 'properties': {'mag': 4.6, 'felt': 1, 'alert': None}, 'geometry': {'coordinates': [122.5991, 8.8699, 10]}}, {'id': 'us6000pw8e', 'properties': {'mag': 4.4, 'felt': None}, 'geometry': {'coordinates': [-68.546, -21.7883, 123.298]}}]}, 'metadata.next')returnsNone