Skip to content

Instantly share code, notes, and snippets.

@kkweon
Last active February 1, 2018 23:53
Show Gist options
  • Save kkweon/fa539440a7af0d41dd190469a15e3389 to your computer and use it in GitHub Desktop.
Save kkweon/fa539440a7af0d41dd190469a15e3389 to your computer and use it in GitHub Desktop.

Implement get-in

https://clojuredocs.org/clojure.core/get-in

from typing import List, Optional


def get_in(data: dict, keywords: List[any]) -> Optional[any]:
    """Implementation of `get-in` in clojure

    Args:
      data (dict): Associative Structure or List
      keywords (List[any]): A sequence of keys

    Returns:
      any: value found else None is returned
    """

    _data = data

    for k in keywords:
        if k in _data:
            _data = _data[k]
        elif isinstance(k, int) and isinstance(_data, list) and len(_data) >= k:
            _data = _data[k]
        else:
            return None

    return _data


m = {
    "username": "sally",
    "profile": {
        "name": "Sally Clojurian",
        "address": {
            "city": "Austin",
            "state": "TX"
        }
    }
}

assert get_in(m, ["profile", "name"]) == "Sally Clojurian"
assert get_in(m, ["profile", "address", "city"]) == "Austin"
assert get_in(m, ["profile", "address", "zip-code"]) is None

v = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

assert get_in(v, [0, 2]) == 3
assert get_in(v, [2, 1]) == 8

mv = {
    "username":
    "jimmy",
    "pets": [{
        "name": "Rex",
        "type": "dog"
    }, {
        "name": "Sniffles",
        "type": "hamster"
    }]
}

assert get_in(mv, ["pets", 1, "type"]) == "hamster"

print("Test passed")
Test passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment