Reputation: 55
I have a function (let's call it foo
):
def foo(**kwargs):
if kwargs.get("key") is not None:
key = kwargs["key"]
else:
key = "default"
Here I have a default value for key
but if kwargs
has a value for key
, I want to use that instead.
Is there a way to simplify this onto 1/2 lines?
Upvotes: 2
Views: 3364
Reputation: 459
Use default value of dict.get
def foo(**kwargs):
key = kwargs.get("key", "default")
Upvotes: 4
Reputation: 981
kwargs
is essentialy of dict
type. As such, the standard way (and the best-practise) of defaulting the value for a non-existent key is by using:
kwargs.get(key, default_val)
Upvotes: 0