karthik
karthik

Reputation: 69

how to convert list of strings into list of dictionaries values

I have a list as below:

list=["a","b","c"]

I want to convert into below format:

data=[{"key": "a"},{"key": "b"},{"key": "c"}]

how to achieve this?

Upvotes: 2

Views: 112

Answers (3)

Jamiu S.
Jamiu S.

Reputation: 5731

It's not appropriate to name your variable list because it's a python built-in function. If you look at my answer you will realize that I have used the built-in list function. You can also choose to avoid iteration like for-loop if you wish to, by using map and lambda:

my_list = ["a", "b", "c"]

data = list(map(lambda x: {"key": x}, my_list))
print(data)

[{'key': 'a'}, {'key': 'b'}, {'key': 'c'}]

Upvotes: 3

Gor Grigoryan
Gor Grigoryan

Reputation: 362

You can use a list to create a new list of dictionaries, each with a key of "key" and a value from the original list, here is an example

givenList = ["a", "b", "c"]
resultList = []
for item in givenList:
    resultList.append({"key": item})

Upvotes: 2

Meny Issakov
Meny Issakov

Reputation: 1421

my_list = ["a", "b", "c"]
list_of_dicts = [{"key": value} for value in my_list]

#output
[{'key': 'a'}, {'key': 'b'}, {'key': 'c'}]

Upvotes: 5

Related Questions