I am trying to get the value of an user input defined key from nested dictionary. While I am able to print out the value from the function itself. Return statement sends value as 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)
Sunder R
1,1141 gold badge9 silver badges22 bronze badges
-
This is the output of code execution: --> place None Process finished with exit code 0vicky_loves_to_code– vicky_loves_to_code2019年01月05日 09:35:37 +00:00Commented Jan 5, 2019 at 9:35
-
have you tried my answerSunder R– Sunder R2019年01月05日 10:00:44 +00:00Commented Jan 5, 2019 at 10:00
2 Answers 2
Line three of your code snippet should read
return getfromdict(newdict, mykey)
To find a leaf in a tree, well, you can, for istance,
def leaf(tree, key):
if key in tree: return tree[key]
for subtree in filter(lambda s: isinstance(s, dict), tree.values()):
ret_val = leaf(subtree, key)
if ret_val is not None: return ret_val
This implementation has the property that if a key is found at some level, whatever it points to is returned, either a leaf or a subtree (in undesired, a fix is quite straightforward).
answered Jan 5, 2019 at 8:30
bipll
12k1 gold badge21 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Sunder R
have you tried running the code, it won't work as it will get excited in the first nested loop itself
You can try this to search the keys in the nested 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
answered Jan 5, 2019 at 9:17
Sunder R
1,1141 gold badge9 silver badges22 bronze badges
1 Comment
Sunder R
can you mark this solution as answered, because the other solution is misleading is misleading
lang-py