After a few days I still cannot figure out how to make this work on python (not an experienced programmer). Here it is the code pasted and at the bottom, the expected result:
color_list = ["red", "blue", "orange", "green"]
secuence = ["color", "price"]
car_list = []
def create_list(color_list, secuence, car_list):
for num in range(len(color_list)):
car_list.append = dict.fromkeys(secuence)
car_list[%s]['color'] = color_list[%s] %num
return car_list
This is the result I want to achieve:
>> car_list
[{'color': 'red', 'price': None},{'color': 'blue', 'price': None},{'color': 'orange', 'price': None},{'color': 'green', 'price': None}]
2 Answers 2
You can do it all in one line for this particular scenario, assuming that 'color' and 'price' are constants.
car_list = [{'color': color, 'price': None} for color in color_list]
See list comprehension - it's a powerful tool.
If you also had a list of prices, price_list, you could do something similar:
car_list = [{'color': color, 'price': price} for color, price in zip(color_list, price_list)]
See the built in function zip().
If the strings 'color' and 'price' are unknown at the time of execution (which I think is unlikely), you could do something similar to the following
car_list = [{secuence[0]: color, secuence[1]: price} for color, price in zip(color_list, price_list)]
3 Comments
Try the following I'm not sure your can use key addressing not but here I have used it.
def create_list(color_list, secuence, car_list):
for each in color_list:
tmp = dict.fromkeys(secuence)
tmp['color'] = each
car_list.append(tmp)
return car_list