Brad
Brad

Reputation: 6342

is it possible to get a grandchild dict key's value without iterating

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

Answers (3)

iamauser
iamauser

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

Ethan Coon
Ethan Coon

Reputation: 771

With a standard dictionary, and not iterating? No.

Upvotes: 0

falsetru
falsetru

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

Related Questions