Function for accessing and searching dictionaries using /slashed/paths (like xpath) So I have some data being returned to me in the form of a deeply nested Dict and I need to parse multiple values from it which may or may not be there. I saw this library (https://github.com/akesterson/dpath-python) and tried to come up with a simplified version that fits into one function.
I think its pretty good but I'm wondering if I missed something or there's some small way to improve it?
from typing import Dict, Union
import re
import copy

def dict_query(d: Dict, path: str) -&gt; Union[object, None]:
    &quot;&quot;&quot;
    # Example usage:
    &gt;&gt;&gt; d = {'a': [{}, {'b': 9}]}
    &gt;&gt;&gt; print( dict_query(d, 'a/[1]/b') )
    9
    &quot;&quot;&quot;
    keys = path.split(&quot;/&quot;)
    val = copy.deepcopy(d)
    for key in keys:

        idx = re.search(&quot;\[(\d+)\]&quot;, key)
        if idx:
            # handle list index
            if isinstance(val, (list, tuple)):
                idx = int(idx.group(1))
                val = val[idx]
            else:
                return None
        elif isinstance(val, dict):
            # handle dict key
            val = val.get(key)
        else:
            return None
    return val

# tests of searching nested dicts
d = {'a': {'b': 1}}
print( dict_query(d, 'a/b') ) # 1
print( dict_query(d, 'a/c') ) # None
print( dict_query(d, 'a/') ) # None
print( dict_query(d, 'c/b') ) # None
# tests of searching nested dicts + lists
d = {'a': [{}, {'b': 1}]}
print( dict_query(d, 'a/[0]') ) # {}
print( dict_query(d, 'a/[1]') ) # {'b': 1}
print( dict_query(d, 'a/[1]/b') ) # 1
print( dict_query(d, 'a/[1]/c') ) # None
print( dict_query(d, 'a/[0]/a') ) # None
print( dict_query(d, '[1]/b') ) # None
I would skip the [] in the path.  Just presume val is a dict with strings for keys (the usual case).  It that doesn't work, try converting the key to an int.
def dict_query(d: Dict, path: str) -&gt; Union[object, None]:
    &quot;&quot;&quot;
    # Example usage:
    &gt;&gt;&gt; d = {'a': [{}, {'b': 9}]}
    &gt;&gt;&gt; print( dict_query(d, 'a/1/b') )
    9
    &quot;&quot;&quot;
    keys = path.split(&quot;/&quot;)
    val = d

    try:
        for key in keys:
            try:
                val = val[key]
                
            except (KeyError, TypeError):
                val = val[int(key)]
        
        return val
    
    except (IndexError, KeyError, TypeError, ValueError):
        return None