1

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
asked Jan 5, 2019 at 8:28
2
  • This is the output of code execution: --> place None Process finished with exit code 0 Commented Jan 5, 2019 at 9:35
  • have you tried my answer Commented Jan 5, 2019 at 10:00

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

have you tried running the code, it won't work as it will get excited in the first nested loop itself
0

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

1 Comment

can you mark this solution as answered, because the other solution is misleading is misleading

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.