所以我有这个json文件:

{
    "participantIdentities": [
        {
            "player": {
                "summonerName": "C9 Kev",
                "summonerId": "scIpmmwEKJpPGi2DZLylEbmhrSjfkBMcoxYyeamiUc2tUu8",
                "accountId": "i9_bugepKjVwgGwi9HoTAxp_vhTQh9KU3pl9TZYFcyb9xQ"
            },
            "participantId": 1
        },
        {
            "player": {
                "summonerName": "R0YALEwCHEESE",
                "summonerId": "CT8AMcHE9bD6URaW39rndvRWI0mntBfjbwy9VkC7DF6L2ao",
                "accountId": "Wqe588a6pGsdG-UB1LYRam_kOD8gcBMGT53O6fOYQSmN7rE"
            },
            "participantId": 2
        }
    ]
}


这是我要完成的工作:

搜索预定的“ summonerName”值,并返回以下“ participantId”。

例如:
我搜索“ C9 Kev”并返回“ 1”(“ participantId”)。

最佳答案

如果for键的participantIdentities键等于您所使用的键,则可以使用participantId循环遍历summonerName键下的子列表并输出player键的值。寻找:

for participant in d['participantIdentities']:
    if participant['player']['summonerName'] == 'C9 Kev':
        print(participant['participantId'])


因此,给定:

d = {
    "participantIdentities": [
        {
            "player": {
                "summonerName": "C9 Kev",
                "summonerId": "scIpmmwEKJpPGi2DZLylEbmhrSjfkBMcoxYyeamiUc2tUu8",
                "accountId": "i9_bugepKjVwgGwi9HoTAxp_vhTQh9KU3pl9TZYFcyb9xQ"
            },
            "participantId": 1
        },
        {
            "player": {
                "summonerName": "R0YALEwCHEESE",
                "summonerId": "CT8AMcHE9bD6URaW39rndvRWI0mntBfjbwy9VkC7DF6L2ao",
                "accountId": "Wqe588a6pGsdG-UB1LYRam_kOD8gcBMGT53O6fOYQSmN7rE"
            },
            "participantId": 2
        }
    ]
}


输出:1

10-06 10:34