Skip to main content
added 306 characters in body
Source Link
enigma
  • 3.5k
  • 2
  • 19
  • 31

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)] 

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.

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)] 
Source Link
enigma
  • 3.5k
  • 2
  • 19
  • 31

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.