-1

I have a list with keys from an array/dictionary:

 keys = ["key1", "key2", "key3"]

My dict looks like this

 {"key1": 
      {
         "key2": 
             {
                "key3": "Value I want to receive"
             }
      }
 }

I need a function that returns dict["key1"]["key2"]["key3] or "False" if its not valid. For the latter I can use try, except I think? I can't figure it out and I don't want to use eval().

Any ideas?

newbypyth
  • 91
  • 1
  • 1
  • 8
  • Did you try to write any code for it? You say you want to iterate through the keys; do you know how to iterate at all? If you want to get the `dict["key1"]["key2"]["key3"]` result - supposing it exists - and you have a list like `["key1", "key2", "key3"]` - what will be the first value you get from the list when you iterate? What do you think you should do with that value? Can you think of the code structure to repeat the process? – Karl Knechtel Apr 10 '21 at 23:02
  • "or "False" if its not valid. For the latter I can use try, except I think?" Are you familiar with the `get` method of dictionaries? – Karl Knechtel Apr 10 '21 at 23:03
  • No, I don't know the get-methodes. – newbypyth Apr 10 '21 at 23:17

1 Answers1

0
keys = ["key1", "key2", "key3"]

my_dict = {"key1": 
               {
                   "key2": 
                       {
                           "key3": "Value I want to receive"
                       }
                }
           }

# return the element in case all keys exists or False otherwise
def get_third_key(d, key1, key2, key3):
    if (key1 in d) and (key2 in d.get(key1)) and (key3 in d.get(key1).get(key2)):
        return d.get(key1).get(key2).get(key3)
    return False

# now you can call get_third_key on given arguments
print(get_third_key(my_dict, *keys))

Evaluating condintions within if statement is according to defenition, which mean they will be evaluated from left to right (hence you don't need try\except blocks).

Using d.get will cause the if statement to fail if key is not a key in relevant dictionary, instead of throwing KeyError Exception (that can happen while using [] operator).

p.s - * operator unpacks the keys list, and specify each positional parameter in the function.

Hook
  • 355
  • 1
  • 7
  • Well, this way the list with keys is not iterable.. – newbypyth Apr 10 '21 at 23:16
  • The list is iterable by definition. Do you mean you *have to* iterate on list and find the value during iteration? otherwise your question is not clear. – Hook Apr 10 '21 at 23:20
  • Well, if I hardcoded the list, I could just hardcode the keys, right? Of course I need to iterate through the keys list. – newbypyth Apr 11 '21 at 14:53