在嵌套字典中返回特定值

时间:2019-05-07 14:52:38

标签: python-3.x dictionary

我有一个嵌套的字典,如下:

myGame = {
          "Soccer": {
                     "T_id": 0,
                     "T_state": "valid",  
                     "Clubs": {
                                "ClubA": 
                                {
                                "T_id": "1",                                
                                "T_state": "Champs"
                                },
                                 "ClubB": 
                                {
                                "T_id": "2",                                
                                "T_state": "Runnerups"
                                }
                             },
                     "Subs": {
                                "SubA": 
                                {
                                "T_id": "3",                                
                                "T_state": "Unfit"
                                }                                
                           }
                  }
            }

我希望只返回

{ "T_id": 0,
  "T_state": "valid"
}

当我进行查询以查找与键“ Soccer”相关联的值时,而不是返回嵌套字典中的所有键和值。 我尝试使用以下代码,但是它返回了完整的词典。有人可以引导我吗?

#note: searchkey is "Soccer" in this case and myGame is the dcitionary
    def getDic(searchkey, myGame ):
        for k in searchkey:
            myGame  = myGame .get(k)
        return myGame 

1 个答案:

答案 0 :(得分:0)

def getDic(searchkeys, myGame):
     new_dict = {}
     for key, item in myGame['Soccer'].items():
          if key in searchkeys:
               new_dict.update({key: item})
     return new_dict

searchkeys = ["T_id","T_state"]
print (getDic(searchkeys,myGame))

输出:

{'T_id': 0, 'T_state': 'valid'}