How can I turn a list of values to a list of dictionaries with the same key added to each value?

Viewed 52

Let's say I have this list of IDs/values:

Input:

['aaa','bbb','ccc']

I've been stuck on figuring out how I could get the following list of dictionaries. Each dictionary contain the key "id" paired with each of the IDs/values from the list.

Desired Output:

[{'id': 'aaa'}, {'id': 'bbb'}, '{id': 'ccc'}]
4 Answers

You can create a list of dictionaries with a list comprehension:

list_ = ['aaa','bbb','ccc']
output = [{'id': elem} for elem in list_]

You can use list slicing concepts here to get your result.

list1 = ['aaa','bbb','ccc']
finalOutput = [{'id': value} for value in list1]

you can loop and append those dictionaries to list like this:

some_list = ['aaa', 'bbb', 'ccc']
dictionary_list = []

for i in some_list:
    dictionary_list.append({'id': i})

You will get a list like you wanted.

['aaa','bbb','ccc']
#place the word 'ID' in front of each element in the list
['ID: '+x for x in ['aaa','bbb','ccc']]
Related