API中Python字典的KeyError

2024-06-13 06:14:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如何调用字典中包含项的特定列表?我想在station列表中使用键name,并输出Richmond。我使用的一个教程已经过时了,所以我能做的最好的事情就是打印钥匙和物品的循环:

for key, value in data.items():
    print(key, value)

这显示了最外层的两个键(?xmlroot),但是我想访问嵌套的字典。你知道吗

我想要的是:

for item in data['station']
    print(item['name'])

>>> Richmond

相反,我用station得到KeyError。既然?xmlroot是用循环标识的键,我假设我需要一个嵌套循环,首先遍历root键,然后访问station,然后使用键name打印Richmond。你知道吗

API结果:

{
    "?xml": {
        "@version": "1.0",
        "@encoding": "utf-8"
    },
    "root": {
        "@id": "1",
        "uri": {
            "#cdata-section": "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=RICH&json=y"
        },
        "date": "10/14/2017",
        "time": "07:50:17 PM PDT",
        "station": [{
            "name": "Richmond",
            "abbr": "RICH",
            "etd": [{
                "destination": "Warm Springs",
                "abbreviation": "WARM",
                "limited": "0",
                "estimate": [{
                    "minutes": "4",
                    "platform": "2",
                    "direction": "South",
                    "length": "6",
                    "color": "ORANGE",
                    "hexcolor": "#ff9933",
                    "bikeflag": "1",
                    "delay": "0"
                }, {
                    "minutes": "24",
                    "platform": "2",
                    "direction": "South",
                    "length": "6",
                    "color": "ORANGE",
                    "hexcolor": "#ff9933",
                    "bikeflag": "1",
                    "delay": "0"
                }]
            }]
        }],
        "message": ""
    }
}

Tags: keynamein列表fordata字典value