pythondpath

How to avoid KeyError when working with dpath?


I'm using dpath to access nested dictionaries in a much cleaner way.

With dpath I can do:

result = dpath.util.get(data, "/data/attributes/policy_revision/policy")

Instead of:

result = data.get("data", {}).get("attributes", {}).get("policy_revision", {}).get("policy", "")

However, the only problem using dpath is that I'm getting a KeyError when any of the keys in the path doesn't exist. Whereas using the get allows me to specify the default value in case the key is not found.

I could try to capture the KeyError exception but that would make code a lot longer and complex, losing the tidiness that dpath initially gives me.

My question is, how can I specify the default value in dpath?

This is their documentation but I haven't found anything related: https://pypi.org/project/dpath/


Solution

  • you can find how they handle default value in their github repo:

    https://github.com/dpath-maintainers/dpath-python/blob/master/dpath/util.py

    line:148,173~175

    code:

    import dpath.util
    x = {
        "a": {
            "b": {
            "3": 2,
            "43": 30,
            "c": [],
            "d": ['red', 'buggy', 'bumpers'],
            }
        }
    }
    print(dpath.util.get(x, '/a/b/42', default = -1))
    print(dpath.util.get(x, '/a/b/43', default = -1))
    

    result:

    -1
    30