Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python using strings as dict keys

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?

like image 312
MKUltra Avatar asked May 28 '26 09:05

MKUltra


2 Answers

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

OUTPUT:

[{'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.

like image 73
Nk03 Avatar answered May 31 '26 08:05

Nk03


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'


like image 30
Stryder Avatar answered May 31 '26 07:05

Stryder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!