Fetching Nested Value Given Dot Notation
I have the following structure in my json: obj = { 'Name': 'David', 'Car': { 'Make': 'Ford', 'Year': 2008 } } I am given dot notation to refer to the
Solution 1:
obj = {
'Name': 'David',
'Car': {
'Make': 'Ford',
'Year': 2008
}
}
s = "Car.Make"x = obj
keys = s.split(".")
for key in keys:
x = x[key]
print(x)
Result:
Ford
Or, in one-liner form:
from functools import reduce
print(reduce(lambda a,b: a[b], s.split("."), obj))
Post a Comment for "Fetching Nested Value Given Dot Notation"