0

Folks, I am using solution described at following location How to use a dot "." to access members of dictionary?

I will minimize the solution here to explain the objective. Basically I am looking for a solution that can take nested keys structure in string format from the user and queries dictionary. I used solution above to convert dictionary in dot notation searchable format. However following is where I am stuck

data = {
"Country" : {
    "US" : [ {"Connecticut" : "Hartford"} , {"California" : "Sacramento"} ]
}

### Following works
f = Map(data)
print(f.Country.US[1].California)

Sacramento

### Following does not work
s = 'Country.US[1].California'
print(f[s])

What I need is a solution that could take externally provided key structure and turns into searchable dot-notation

What can be done?

Ozzie Ghani
  • 193
  • 2
  • 13
  • So you want to input `'Country.US[1].California'` and output `'Sacramento'`? – 001 Aug 26 '22 at 17:21
  • yes, The input will be string – Ozzie Ghani Aug 26 '22 at 17:27
  • the janky and basic way would be to use exec to treat the string as a variable `exec(f"print(f.{s})")` – benjababe Aug 26 '22 at 17:35
  • You can use `eval` but need to process the input string a bit to convert to a format like: `"['Country']['US'][1]['California']"`. Something like: `eval("data" + '[' + "][".join([f"{x[:-1]}" if ']' == x[-1] else f"'{x}'" for x in re.split(r"[\.\[]", s)]) + "]")` – 001 Aug 26 '22 at 17:46
  • @benjababe solution seems to work but its print statement, what I need to do is return the result from queried dictionary back to other app. so somehow exec(f"print(f.{s})") needs to be saved in variable and so I can return. Any suggestion there. – Ozzie Ghani Aug 29 '22 at 02:01

0 Answers0