I'm trying to write a very simple function to recursively search through a possibly nested (in the most extreme cases ten levels deep) Python dictionary and return the first value it finds from the given key.
I cannot understand why my code doesn't work for nested dictionaries.
def _finditem(obj, key):
if key in obj: return obj[key]
for k, v in obj.items():
if isinstance(v,dict):
_finditem(v, key)
print _finditem({"B":{"A":2}},"A")
It returns None
.
It does work, however, for _finditem({"B":1,"A":2},"A")
, returning 2
.
I'm sure it's a simple mistake but I cannot find it. I feel like there already might be something for this in the standard library or collections
, but I can't find that either.
dict
object is a bad idea, as it rules outdict
-like objects. Instead, dotry: ...
except TypeError: ...
. (Ask for forgiveness, not permission). - Gareth Latty