How do you iterate over keyword arguments in a Python function? For example, say I have the following method:
class Car():
def start_engine(self, key, *, driver=None, passenger=None, gas=None):
for k,v in <ITERATE_OVER_KEYWORD_ARGUMENT>:
if v is not None:
print(f"KEY: {k} VALUE:{v}")
c = Car()
c.start_engine(key, driver="Bob", passenger="Alice")
Should print:
driver: Bob
passenger: Alice
I didn't want to use **kwargs
because I wanted to name my arguments.
I can't just call locals()
because I have other arguments.
I guess I could make a helper function that takes in **kwargs
and then build a dict, and then I'd call that function with all my keyword arguments, but that seems hacky.
def to_dict(**kwargs):
d = {k:v for k,v in kwargs.items() if v is not None}
return d
That works, but seems like such a strange way to accomplish what I'm trying to do.
Is there an acceptable way to to iterate through keyword arguments, or is that bad Python for some reason?