0

I want to extract the value out of nested dictionary in python. The main issue is I want to pass the extraction set as a string from config file where a user can pass their own command and we extract the value out of it. Dictionary is something like

d = {"a": {"b": [ {"c": "apple"}]}}

I want to extract the value of c but I want to pass the command as a string from outside possibly a config file which gives user control to extract whichever information they want. For example a user can pass string "['a']['b'][0]['c']" or user can pass ['a']['b'] or anything and we return the value present in the dict on that path

Now I know there is eval present in python. But is there a better way that this? I have tried using eval and it works fine but as we all know they are evil and should be avoided. Is there a better way

  • 1
    This question is hard to understand. What is an `"extraction set"`? What is the string you intend to pass? This isn't just a nested dict. It also has a list of dicts. It would be really helpful to give exactly what you are starting with and what you want in the end? – Mark Mar 24 '22 at 21:52
  • 1
    Assuming the user can provide a complete path, you want some function `f` so that, say, `f("a", "b", 0, "c") == d["a"]["b"][0]["c"]`? – chepner Mar 24 '22 at 21:52
  • @Mark I have updated the question with example. Please review it again if possible – Rahul Khanna Mar 25 '22 at 04:49
  • 1
    @RahulKhanna the duplicate in the link actually has really good answers for this. – Mark Mar 25 '22 at 05:05

0 Answers0