从嵌套的字典列表中的键获取值

Get value from key within nested Lists of Dicts

我是 Python 的新手,一直在尝试打印出 JSON 的嵌套字典列表中存在的键所附加的值。这是我所知道的结构:

details - List of dicts

scorecardDetails - List of dicts

scorecard - Dict

playerHandicap - Key:Value

还值得注意的是,还有一个名为 'summary' 的列表与 'details' 处于同一级别。

这是我目前所在的位置,但我正在努力找出如何确定我只想查看 'playerHandicap' 键:

details_list = json_load['details']

for index in range(len(details_list)):
    for key in details_list[index]:
        print(details_list[index][key])

这是 JSON 的快照(所需的 key/value 对在 'scorecard' 字典中,它有多个):

"details":[
      {
         "startTime":"2021-03-16T12:16:16.000Z",
         "formattedStartTime":"2021-03-16T12:16:16Z",
         "scorecardDetails":[
            {
               "scorecard":{
                  "id":172482642,
                  "customerId":"******",
                  "playerProfileId":*****,
                  "roundPlayerName":"*******",
                  "connectDisplayName":"********",
                  "courseGlobalId":21042,
                  "courseSnapshotId":43716,
                  "frontNineGlobalCourseId":21042,
                  "scoreType":"STROKE_PLAY",
                  "useHandicapScoring":true,
                  "useStrokeCounting":false,
                  "startTime":"2021-03-16T12:16:16.000Z",
                  "formattedStartTime":"2021-03-16T12:16:16Z",
                  "endTime":"2021-04-23T09:09:47.000Z",
                  "formattedEndTime":"2021-04-23T09:09:47Z",
                  "unitId":"1",
                  "roundType":"ALL",
                  "inProgress":false,
                  "excludeFromStats":false,
                  "holesCompleted":18,
                  "publicRound":false,
                  "score":29,
                  "playerHandicap":0,
                  "courseHandicapStr":"061018120208141604010709111517031305",
                  "teeBox":"null",
                  "handicapType":"MEN",
                  "teeBoxRating":73.03,
                  "teeBoxSlope":118,
                  "lastModifiedDt":"2021-04-23T09:09:46.000Z",
                  "sensorOnPutter":false,
                  "handicappedStrokes":101,
                  "strokes":101,

我确信这是一个简单的解决方案,但我很难理解不同级别的循环!谢谢:)

我不确定你的问题。

您可以使用 dict.keys() 获取字典中的所有键。

这里可能会有一个回应:

dict_test = {"details":[
      {
         "startTime":"2021-03-16T12:16:16.000Z",
         "formattedStartTime":"2021-03-16T12:16:16Z",
         "scorecardDetails":[
            {
               "scorecard":{
                  "id":172482642,
                  "customerId":"6300102921355894",
                  "playerProfileId":62337607,
                  "roundPlayerName":"*******",
                  "connectDisplayName":"5536cd4a-f35e-4034-966c-a5d8238a8c26",
                  "courseGlobalId":21042,
                  "courseSnapshotId":43716,
                  "frontNineGlobalCourseId":21042,
                  "scoreType":"STROKE_PLAY",
                  "useHandicapScoring":True,
                  "useStrokeCounting":False,
                  "startTime":"2021-03-16T12:16:16.000Z",
                  "formattedStartTime":"2021-03-16T12:16:16Z",
                  "endTime":"2021-04-23T09:09:47.000Z",
                  "formattedEndTime":"2021-04-23T09:09:47Z",
                  "unitId":"1",
                  "roundType":"ALL",
                  "inProgress":False,
                  "excludeFromStats":False,
                  "holesCompleted":18,
                  "publicRound":False,
                  "score":29,
                  "playerHandicap":0}}]}]}
                  
details_list = dict_test['details']

for index in details_list:
    for dict_ in details_list:
        for key_ in dict_.keys():
            print(dict_[key_])

下面的代码可以帮到你

for item in json_load['details']:
    for scorecardDetail in item['scorecardDetails']:
        if 'playerHandicap' in scorecardDetail['scorecard']: 
            print(scorecardDetail['scorecard']['playerHandicap'])

优雅的解决方案是使用 jmespath 它还将处理密钥不存在的情况

pip install jmespath

如果您有 data 作为正确的字典,那么我们可以使用

import jmespath
expression = jmespath.compile('details[*].scorecardDetails[*].scorecard.playerHandicap')
# this expression will look in each detail then each scorecardDetails then in each scorecard it will fetch playerHandicap
res = expression.search(data)
print(res)  # this will print the list of values from all records