从data大字典中找出特定键GlossTerm
的value值
题目来自面试笔试题
我的思路是先将json格式data序列化得到字典格式data
然后递归遍历
找到目标键后退出递归并返回它的值
import json
data = json.loads(data)
def get_key_node(dict_data,obj_key):
for key,value in dict_data.items():
if value:
if not isinstance(value,dict):
if key==obj_key:
print(value)
return value
else:
get_key_node(value,obj_key)
print(get_key_node(data,"GlossTerm"))
data = '''{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}'''
import json
data = json.loads(data)
def get_key_node(dict_data,obj_key):
for key,value in dict_data.items():
if value:
if not isinstance(value,dict):
if key==obj_key:
print(value)
return value
else:
get_key_node(value,obj_key)
print(get_key_node(data,"GlossTerm"))
期待的结果是
'Standard Generalized Markup Language
可我的方法结果是
None
翻翻过去那场雪
米琪卡哇伊
相关分类