Home > OS >  How to add a fixed key for each element of list in python?
How to add a fixed key for each element of list in python?

Time:10-13

I have a list like this:

student = ["James", "Abhinay", "Peter"]

I don't know how I can add a fixed key for each element of list in python?

what I want:

[{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]

CodePudding user response:

Try using a list comprehension:

>>> [{'name': x} for x in student]
[{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]
>>> 

Or map:

>>> list(map(lambda x: {'name': x}, student))
[{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]
>>> 
  • Related