1

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

3

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)] 
Sign up to request clarification or add additional context in comments.

3 Comments

what if I also wanted to asign something to 'price'? (what I want to asign to it is in a different list)
@BlenderUser the second section of my answer should answer that for you. If I have misunderstood what you mean, could you clarify?
Yes, that's exactly!! Srry
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.