Search code examples
pythonclojure

Is there a python function like Clojure's get-in?


Is there something equivalent to Clojure's get-in function in Python? It gets the data at the given path in some data structure.

In Clojure it is used like:

(def employee
  {:name "John"
   :details {:email "[email protected]"
             :phone "555-144-300"}})

(get-in employee [:details :email])  ; => "[email protected]"

If translated to Python syntax it would be used like:

dictionary = {'a': {'b': 10}}
get_in(dictionary, ['a', 'b'])  # => 10

This function is used to access arbitrary data points in nestled data structures where the paths are not known at compile time, they are dynamic. More usage examples of get-in can be found on clojuredocs.


Solution

  • You can write:

    dictionary.get('details', {}).get('email')
    

    This will safely get the value you need or None, without throwing an exception - just like Clojure's get-in does.

    If you need a dedicated function for that, you can write:

    def get_in(d, keys):
        if not keys:
            return d
        elif len(keys) == 1:
            return d.get(keys[0])
        else:
            return get_in(d.get(keys[0], {}), keys[1:])