Consider the following dict:
{
"a" : {
"b" : [
entry,
entry,
...
]
}
}
Is there any way to address each entry given a key in the form "a.b"
?
Ideally one could write something like dict[*("a.b".split("."))]
and get dict["a"]["b"]
, but I have found no way to do it in Python yet.
Edit 2
Since no one seems to really care about quality code, I ended up using a plain old for loop:
data = { "a" : { "b" : "foo" } }
key = "a.b"
d = data
for k in key.split("."):
d = d[k]
d == data["a"]["b"] # True
Edit 3
Comments contain a valid solution:
import operator
from functools import reduce # forward compatibility for Python 3
data = { "a" : { "b" : "foo" } }
key = "a.b"
d = reduce(operator.getitem, key.split("."), data)
d == data["a"]["b"] # True
However, apart from this, I guess there is no way to exploit some language feature to do that, which kind of was the original question.