Необходимо упростить код

Суть вопроса в следующем: извлекаются данные из большого словаря и добавляются в соответствующие списки. Как можно максимально упростить эту конструкцию? UPD: Добавил начало кода, изменить нужно, начиная с пустых списков

import json

from plotly.graph_objs import Scattergeo, Layout
from plotly import offline

# Изучение структуры данных.
filename = 'D:\УчёБА\Python c 0 до Pro\Визуализация данных\data\eq_data_30_day_m1.json'
with open(filename) as f:
    all_eq_data = json.load(f)

all_eq_dicts = all_eq_data['features']

mags, lons, lats, hover_texts = [], [], [], []
for eq_dict in all_eq_dicts:
    mag = eq_dict['properties']['mag']
    lon = eq_dict['geometry']['coordinates'][0]
    lat = eq_dict['geometry']['coordinates'][1]
    title = eq_dict['properties']['title']
    mags.append(mag)
    lons.append(lon)
    lats.append(lat)
    hover_texts.append(title)

Вот фрагмент этого словаря:

{
"type": "FeatureCollection",
"metadata": {
    "generated": 1550361510000,
    "url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_month.geojson",
    "title": "USGS Magnitude 1.0+ Earthquakes, Past Month",
    "status": 200,
    "api": "1.7.0",
    "count": 6274
},
"features": [
    {
        "type": "Feature",
        "properties": {
            "mag": 0.96,
            "place": "8km NE of Aguanga, CA",
            "time": 1550360775470,
            "updated": 1550360993593,
            "tz": -480,
            "url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci37532978",
            "detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/ci37532978.geojson",
            "felt": null,
            "cdi": null,
            "mmi": null,
            "alert": null,
            "status": "automatic",
            "tsunami": 0,
            "sig": 14,
            "net": "ci",
            "code": "37532978",
            "ids": ",ci37532978,",
            "sources": ",ci,",
            "types": ",geoserve,nearby-cities,origin,phase-data,",
            "nst": 32,
            "dmin": 0.02648,
            "rms": 0.15,
            "gap": 37,
            "magType": "ml",
            "type": "earthquake",
            "title": "M 1.0 - 8km NE of Aguanga, CA"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [
                -116.7941667,
                33.4863333,
                3.22
            ]
        },
        "id": "ci37532978"
    },

Ответы (2 шт):

Автор решения: Stanislav Volodarskiy

Способ сократить повторяющийся код:

def get(a, *keys):

    def get(d, *keys):
        for k in keys:
            d = d[k]
        return d

    return [get(d, *keys) for d in a]


mags = get(all_eq_dicts, 'properties', 'mag')
lons = get(all_eq_dicts, 'geometry', 'coordinates', 0)
lats = get(all_eq_dicts, 'geometry', 'coordinates', 1)
hover_texts = get(all_eq_dicts, 'properties', 'title')
→ Ссылка
Автор решения: Алексей Р

Вариант с pandas

import pandas as pd
import json

txt = '''{
    "type": "FeatureCollection",
    "metadata": {
        "generated": 1550361510000,
        "url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_month.geojson",
        "title": "USGS Magnitude 1.0+ Earthquakes, Past Month",
        "status": 200,
        "api": "1.7.0",
        "count": 6274
    },
    "features": [
        {
            "type": "Feature",
            "properties": {
                "mag": 0.96,
                "place": "8km NE of Aguanga, CA",
                "time": 1550360775470,
                "updated": 1550360993593,
                "tz": -480,
                "url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci37532978",
                "detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/ci37532978.geojson",
                "felt": null,
                "cdi": null,
                "mmi": null,
                "alert": null,
                "status": "automatic",
                "tsunami": 0,
                "sig": 14,
                "net": "ci",
                "code": "37532978",
                "ids": ",ci37532978,",
                "sources": ",ci,",
                "types": ",geoserve,nearby-cities,origin,phase-data,",
                "nst": 32,
                "dmin": 0.02648,
                "rms": 0.15,
                "gap": 37,
                "magType": "ml",
                "type": "earthquake",
                "title": "M 1.0 - 8km NE of Aguanga, CA"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -116.7941667,
                    33.4863333,
                    3.22
                ]
            },
            "id": "ci37532978"
        }]}'''

dct = json.loads(txt)
df = pd.json_normalize(dct, 'features')
msg = df['properties.mag'].tolist()
lon = df['geometry.coordinates'].str[0].tolist()
lat = df['geometry.coordinates'].str[1].tolist()
title = df['properties.title'].tolist()
print(msg, lon, lat, title, sep='\n')
[0.96]
[-116.7941667]
[33.4863333]
['M 1.0 - 8km NE of Aguanga, CA']
→ Ссылка