Reputation: 3668
I want to pass in a value from a dictionary - only if it exists - to my function. If the key, value doesn't exist in this dictionary, I want the method to use its default.
For example, with method m:
def m(a=1, b=2, c=3)
And dictionary d:
d = {"a": 5}
I want to pass in the values of the dictionary into the method if they exist in a one liner. Something like this:
m(a=d["a"] if d.get("a"), b=d["b"] if d.get("b"), c=d["c"] if d.get("c"))
Is there a way to do this in python2 as a one liner? Or am I stuck using multiple if conditions like this:
if d.get("a") and d.get("b") and d.get("c"):
m(a=d["a"], b=d["b"], c=d["c"])
elif d.get("a") and d.get("b"):
m(a=d["a"], b=d["b"])
elif d.get("a"):
m(a=d["a"])
# ...and so on
Upvotes: 0
Views: 47
Reputation: 3668
If I call m(**d)
it works. This is just what I was looking for.
Upvotes: 1