0

This is my python dict:

my_dict={
    "key":{
    "outbound_email_detail":{
        "from":"value"
        }
    }
}

Here is my input String :

input="key#outbound_email_detail#from"

How could I parse my input to access python dict. I tried with the split but not sure how to assemble it back ?

Expected Output is :

print(my_dict["key"]["outbound_email_detail"]["from"])
PiaklA
  • 495
  • 2
  • 7
  • 21
  • My code needs to read "Value" which is dynamic, rest of the dict hierarchy is static. Input String tells me what dict structure I need to navigate to get the "value" – PiaklA May 18 '23 at 20:04
  • `keys = string.split("#")` then `current = my_dict`, then `for key in keys: current = current[key]` then `print(current)` – juanpa.arrivillaga May 18 '23 at 20:08
  • Okay, for some reason I thought you were asking about creating the dict from the string, but you're just asking how to access it. Split the string into a list of keys, and then take a look at [_Access nested dictionary items via a list of keys?_](https://stackoverflow.com/q/14692690/674039). I prefer the second answer to the accepted one. – wim May 18 '23 at 20:10
  • or more tersely: `functools.reduce(lambda acc, key: acc[key],keys, my_dict)` – juanpa.arrivillaga May 18 '23 at 20:13
  • @juanpa.arrivillaga Why are you answering in the comments? – wim May 18 '23 at 20:25
  • @wim because I closed the question, I typically leave an "answer" when I do because I feel it is polite, but if it is not supposed to happen I'll cease to do that and merely point out the linked duplicate – juanpa.arrivillaga May 18 '23 at 20:26
  • @juanpa.arrivillaga Yeah, it is discouraged, in fact the placeholder text before you start typing a comment literally says: ["Avoid answering questions in comments"](https://meta.stackoverflow.com/a/373678). – wim May 18 '23 at 20:36

2 Answers2

1

you can use functools reduce. info here. You have a nice post on reduce in real python

from functools import reduce

reduce(dict.get, input.split("#"), my_dict)
>>> "value"
Lucas M. Uriarte
  • 2,403
  • 5
  • 19
1

Try this:

def parse_input(input_str, input_dict):
    for key in input_str.split("#"):
        input_dict = input_dict.get(key)
    return input_dict

print(parse_input("foo#bar", {"foo": {"bar": "foobar"}})) # foobar