Home > Enterprise >  List of values to list of dictionaries
List of values to list of dictionaries

Time:01-24

I have a list with some string values:

['red', 'blue']

And I want to use those strings as values in single, constant keyed dictionaries. So the output would be:

[{'color': 'red'}, {'color': 'blue'}]

CodePudding user response:

You can convert a list to a list of dictionaries like this:

colors = ["red", "blue"]
colors = [{'color': c} for c in colors]
>>> [{'color': 'red'}, {'color': 'blue'}]

This will create a list of dictionaries by iterating through the list.

Below is exactly the same code, but written in a way most beginners can understand it better:

colors = ["red", "blue"] # get a list of colors
new_colors = [] # create empty list to store final result
for c in colors: # go over each color in colorsarray
    new_colors.append({'color': c}) # append a dictionary to the new_colors array
>>> [{'color': 'red'}, {'color': 'blue'}]

CodePudding user response:

The easiest, and pythonic, way would be a 'comprehension' as follows:

colors = ["red", "blue"]
print(colors)
color_dict = [{"color": x} for x in colors]
print(color_dict)
['red', 'blue']
[{'color': 'red'}, {'color': 'blue'}]

The comprehension creates a new structure from a list or other iterable. In this case, it's constructing a list comprising {"color": x} for every x element in the list.

CodePudding user response:

You can also use map:

colors = ["red", "blue"]
data = [*map(lambda color: {'color': color}, colors)]
print(data)

# [{'color': 'red'}, {'color': 'blue'}]
  • Related