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