我试图从嵌套字典中获取用户输入定义的键的值。虽然我可以从函数本身中打印出值。Return语句将值发送为None。
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: 'James',
4: 'lance',
'change1': {5: 'place'},
'country': {'Waterloo': 'Waterloo', 'Australia': 'Australia'},
6: {'Position': 'GM'}
}
def getfromdict(mydict, mykey):
for i in mydict.keys():
if type(mydict[i])==dict:
newdict = mydict[i]
getfromdict(newdict, mykey)
elif i == mykey:
print(mydict[i])
valuefound = mydict[i]
return valuefound
else:
continue
result = getfromdict(people,5)
print(result)
您可以尝试在嵌套JSON中搜索键
def getfromdict(mydict, mykey):
if type(mydict) == type({}):
for k1 in mydict:
if k1 == mykey:
return mydict[k1]
fromdict = getfromdict(mydict[k1], mykey)
if fromdict is not None:
return fromdict
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句