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

Time:07-09

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'}]

CodePudding user response:

You can run:

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

CodePudding user response:

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

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

CodePudding user response:

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