我有一个嵌套的字典,如下:
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
答案 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'}