topic description
find out the value of a specific key GlossTerm
from the data dictionary
sources of topics and their own ideas
the question comes from the interview pen question
my idea is to serialize the json format data to the dictionary format data
and then recursively traverse
to find the target key and exit the recursion and return its value
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"))
related codes
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"))
what result do you expect? What is the error message actually seen?
the expected result is
"Standard Generalized Markup Language
but the result of my method is
None