无法从词典列表访问嵌套词典

时间:2020-06-12 01:09:05

标签: python list dictionary

我有一个词典列表(对不起,有点复杂,但是我想显示真实数据):

[{'alerts': [{'city': ' city name1',
              'country': 'ZZ',
              'location': {'x': 1, 'y': 3},
              'milis': 1582337463000},
             {'city': ' city name2',
              'country': 'ZZ',
              'location': {'x': 1, 'y': 3},
              'pubMillis': 1582337573000,
              'type': 'TYPE2'}],
  'end': '11:02:00:000',
  'start': '11:01:00:000'},
 {'alerts': [{'city': ' city name3',
              'country': 'ZZ',
              'location': {'x': 1, 'y': 3},
              'milis': 1582337463000}],
  'end': '11:02:00:000',
  'start': '11:01:00:000'}]

通常,列表结构如下:

[
{ [
    { {},
    },
    { {},
    }
  ],
},
{ [
    { {},
    },
    { {},
    }
  ],
}
]

如果我想访问city name1,则可以使用以下代码行进行访问:alerts[0]['alerts'][0]['city']

如果我想访问city name2,可以使用以下代码进行访问:alerts[0]['alerts'][1]['city']

如何循环访问此内容?

3 个答案:

答案 0 :(得分:2)

使用嵌套循环:

  • alerts等于字典列表的地方
for x in alerts:
    for alert in x['alerts']:
        print(alert['city'])

答案 1 :(得分:1)

使用熊猫

  • data等于您的字典示例列表
import pandas as pd

# create the dataframe and explode the list of dicts
df = pd.DataFrame(data).explode('alerts').reset_index(drop=True)

# json_normalize the dicts and join back to df
df = df.join(pd.json_normalize(df.alerts))

# drop the alerts column as it's no longer needed
df.drop(columns=['alerts'], inplace=True)

# output
          start           end country         city         milis  location.x  location.y   type     pubMillis
0  11:01:00:000  11:02:00:000      ZZ   city name1  1.582337e+12           1           3    NaN           NaN
1  11:01:00:000  11:02:00:000      ZZ   city name2           NaN           1           3  TYPE2  1.582338e+12
2  11:01:00:000  11:02:00:000      ZZ   city name3  1.582337e+12           1           3    NaN           NaN

答案 2 :(得分:0)

目标是什么?要获取所有城市名称?

>>> for top_level_alert in alerts:
        for nested_alert in top_level_alert['alerts']:
            print(nested_alert['city'])
city name1
city name2
city name3