List of values to list of dictionaries

Question:

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'}]
Asked By: Atlas91

||

Answers:

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'}]
Answered By: 3dSpatialUser

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.

Answered By: Thickycat

You can also use map:

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

# [{'color': 'red'}, {'color': 'blue'}]
Answered By: Arifa Chan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.