I am learning programming, and I am thinking how to improve this code in a more pythonic way.
I have a function with number of arguments. However, any caller of the function can specify the arguments, and depending on the arguments given, I will return the dictionary. The given arguments must be only from the listed arguments.
The code that I have below has so much duplication (I remove carPower, carTime and carLease however it will do the same if/else part) How can I improve this?
def creating_result(my_struct,
carColour=None,
carPrice=None,
carGas=None,
carBrand=None,
carSpeed=None,
carOwner=None,
carPower=None,
carTime=None,
carLease=None,
carEngine=None,
carType=None
):
if carColour and isinstance(carColour, list):
my_struct["carColour"] = { "thekey" : carColour}
elif carColour:
my_struct["carColour"] = carColour
if carPrice and isinstance(carPrice, list):
my_struct["carPrice"] = { "thekey" : carPrice}
elif carPrice:
my_struct["carPrice"] = carPrice
if carGas and isinstance(carGas, list):
my_struct["carGas"] = { "thekey" : carGas}
elif carGas:
my_struct["carGas"] = carGas
if carBrand and isinstance(carBrand, list):
my_struct["carBrand"] = { "thekey" : carBrand}
elif carBrand:
my_struct["carBrand"] = carBrand
if carSpeed and isinstance(carSpeed, list):
my_struct["carSpeed"] = { "thekey" : carSpeed}
elif carSpeed:
my_struct["carSpeed"] = carSpeed
if carEngine:
my_struct["carEngine"] = carEngine
if carPrice:
my_struct["carPrice"] = carPrice
if carType:
my_struct["carType"] = carType
print "my_struct is ", my_struct
if __name__ == "__main__":
# test 1st caller
my_dict = {}
creating_result(my_dict, carPrice=1, carColour="red")
# test 2nd caller
my_dict = {}
creating_result(my_dict, carSpeed="200", carType="SUV", carPrice=300)
In case I can not change the list of arguments of the function above, how can I improve the (if/else) of the function above?