1

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 object value, for example:

Car.Make ==> 'Form'

Given a string, such as "Car.Make", how would I programmatically fetch the attribute? In the above example, it would be:

obj.get('Car').get('Make')

But what about for a deeply-nested object, how would I extract the value given dot notation of "Attr1.Attr2.Attr3...Attrn" ?

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

5
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))
Kevin
  • 74,910
  • 12
  • 133
  • 166
0

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

Community
  • 1
  • 1
jojonas
  • 1,634
  • 14
  • 24