题目描述从data大字典中找出特定键GlossTerm的value值题目来源及自己的思路题目来自面试笔试题我的思路是先将json格式data序列化得到字典格式data然后递归遍历找到目标键后退出递归并返回它的值importjsondata=json.loads(data)defget_key_node(dict_data,obj_key):forkey,valueindict_data.items():ifvalue:ifnotisinstance(value,dict):ifkey==obj_key:print(value)returnvalueelse:get_key_node(value,obj_key)print(get_key_node(data,"GlossTerm"))相关代码data='''{"glossary":{"title":"exampleglossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"StandardGeneralizedMarkupLanguage","Acronym":"SGML","Abbrev":"ISO8879:1986","GlossDef":{"para":"Ameta-markuplanguage,usedtocreatemarkuplanguagessuchasDocBook.","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}}'''importjsondata=json.loads(data)defget_key_node(dict_data,obj_key):forkey,valueindict_data.items():ifvalue:ifnotisinstance(value,dict):ifkey==obj_key:print(value)returnvalueelse:get_key_node(value,obj_key)print(get_key_node(data,"GlossTerm"))你期待的结果是什么?实际看到的错误信息又是什么?期待的结果是'StandardGeneralizedMarkupLanguage可我的方法结果是None
2 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
我记得回答过你类似的问题?基于你的代码改的defget_dictkeys(dic,find_key):find_value='no'forkey,valueindic.items():ifkey==find_key:find_value=valueelifisinstance(value,dict):find_value=get_dictkeys(value,find_key)iffind_value=='no':return'dictdoesnthavethiskey'else:returnfind_valueprintget_dictkeys(data,"GlossTerm")
添加回答
举报
0/150
提交
取消