【问题标题】:How to access nested dictionary from a list of dictionaries如何从字典列表中访问嵌套字典
【发布时间】:2020-10-01 18:42:43
【问题描述】:

我有一个字典列表(对不起,它有点复杂,但我正在尝试显示真实数据):

[{'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']

如何循环访问它?

【问题讨论】:

    标签: python list dictionary json-normalize


    【解决方案1】:

    使用嵌套循环:

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

    【讨论】:

    • 好的,我认为这不符合我的要求。
    • 循环访问所有城市。不是你说的吗?
    【解决方案2】:

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

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

    【讨论】:

    • 当我应用于实际数据集时它不起作用。它只捕获第一行
    • 我在你的数据结构上运行它,它找到了所有 3 个城市名称...
    • 这与Barmar给出的答案相同
    • 我的想法完全正确。
    【解决方案3】:

    使用熊猫

    • 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
    

    【讨论】:

    • 这正是我需要的!我的计划是将它们放入数据框中。太好了,这可以满足其他字典中没有的字典。
    • 访问嵌套字典可能是个问题。很高兴这对你有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多