Home > database >  How to create `if in` function check?
How to create `if in` function check?

Time:08-01

I have been investigating and found out that using if in is the fastest compare to -> IMAGE

benchmark

and I have been trying to create a function where I can pass arguments on what path I want the if in will follow e.g.

def main():
    d = {"foo": "spam"}
    if "bar" in d:
        if "eggs" in d["bar"]:
            d["bar"]["eggs"]
        else:
            {}
    else:
        {}

But instead of having a long code, I was trying to do a function where I can pass argument e.g. get_path(json_data, 'foo', 'eggs') which would try to do something similar to the code above and return if value found else return empty.

My question is how can I create a function where we can pass argument to do the if in checks and return the value if it's found?

CodePudding user response:

You could pass your keys as tuple/list:

def main(data, keys):
    for k in keys:
        if k not in data:
            return {}
        data = data[k]
    return data


d = {"foo": "spam", "bar": {"eggs": "HAM!"}}
print(main(d, ('bar', 'eggs')))

Out:

HAM!

CodePudding user response:

This is a nice little problem that has a fairly easy solution as long as everything is dicts:

def get_path(data, *path):
    node = data
    for step in path:
        if step in node:
            node = node[step]
        else:
            return {} # None might be more appropriate here
    return node

note that it won't work quite right if you encounter a list along the way: although lists support [] and they support in, in means something different to them ("is this value found", rather than "is this key found"), so the test generally won't succeed.

  • Related