Skip to content Skip to sidebar Skip to footer

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))

Solution 2:

Here are some answers from Stackoverflow that propose a custom dictionary class that implements __getattr__ and __setattr__ to access the dictionary items:

Post a Comment for "Fetching Nested Value Given Dot Notation"