Reputation: 6342
given a dict what contains n number of dictionaries which contain n number of dictionaries etc.
foo = dict({"foo" : {"bar": {"baz": "some value"}}}
assuming baz
could be anywhere in foo
but that it will only occur once, is it possible without iterating to find if the value of the key "baz"? I'm thinking something xpath-ish. ie ".//baz"
if "baz" in foo:
bazVal = dict[path][to][baz]
Upvotes: 0
Views: 296
Reputation: 11479
Without iterating, not sure. With, you can use the following:
d = dict({"foo" : {"bar": {"baz": "some value"}}})
def myprint(d):
for i in d.iteritems():
if isinstance(i, dict):
myprint(i)
else:
print i
myprint(d)
Upvotes: 0
Reputation: 369274
I don't think you can do it without iteration/recursion.
>>> def search(d, baz):
... if baz in d:
... return d[baz]
... for value in d.values():
... if isinstance(value, dict):
... ret = search(value, baz)
... if ret:
... return ret
...
>>>
>>> foo = {"foo" : {"bar": {"baz": "some value"}}}
>>> search(foo, 'baz')
'some value'
>>> search(foo, 'spam')
>>>
Upvotes: 1