Reputation: 69
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
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
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
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