I have an object with a similar structure to this
myObj = {
"subObj1":{"keyA":"valueA1"},
"subObj2":{"keyA":"valueA2","keyB":"valueB2"},
"subObj3":{"keyA":"valueA3","keyB":"valueB3", "keyC":{"keyA":"valueA3c"}},
}
Typically I can access the contents of this object similarly to this
print(myObj['subObj1']['keyA'])
print(myObj['subObj2']['keyB'])
print(myObj['subObj3']['keyC']['keyA'])
Which would return the values
alueA1
valueB2
valueA3c
I need a way to access the contents of my object based on keys from an external configuration file, The key from that file would look like
"subObj3.keyC.keyA"
I can transform that key into something similar to how I usually access the object
keyString="['subObj3']['keyC']['keyA']"
But when attempting to access the object with that keyString I get KeyError messages
print(myObj[keyString])
KeyError: "['subObj3']['keyC']['keyA']"
Is there a proper syntax, or a better way for what I'm trying to do here?
Here's one way via pandas:
import pandas as pd
myObj = {
"subObj1": {"keyA": "valueA1"},
"subObj2": {"keyA": "valueA2", "keyB": "valueB2"},
"subObj3": {"keyA": "valueA3", "keyB": "valueB3", "keyC": {"keyA": "valueA3c"}},
}
normalized_myObj = pd.json_normalize(myObj, sep='.').to_dict('records')
[{'subObj1.keyA': 'valueA1',
'subObj2.keyA': 'valueA2',
'subObj2.keyB': 'valueB2',
'subObj3.keyA': 'valueA3',
'subObj3.keyB': 'valueB3',
'subObj3.keyC.keyA': 'valueA3c'}]
NOTE: using pandas may be overkill for this task, but it's just a one-line solution that I prefer.
Nk03's solution is indeed a powerful method... Just as a simpler alternative, consider this:
def get_value(s):
keys = s.split(".")
d = myObj
for k in keys: d = d[k] # will go a step deeper for each provided key
return d
get_value("subObj3.keyC.keyA")
>> 'valueA3c'
get_value("subObj1.keyA")
>> 'valueA1'
get_value("subObj2.keyB")
>> 'valueB2'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With