Convert a python list into a list of single item dictionaries

Viewed 67

I am trying to figure out the most efficient way to convert a list into a list of single item dictionaries, example:

my_fruit = [
   'apple', 
   'orange',
   'pear',
   'grape'
]

to

my_fruit = [
   {'apple': 'apple'},
   {'orange': 'orange'},
   {'pear': 'pear'},
   {'grape': 'grape'}
]

I'm just not familiar enough with Python to figure out the best way to do this. It seems like it should be easy.

2 Answers
my_fruit = [{x: x} for x in my_fruit] 

will create the desired structure. The purpose of that structure is not immediately clear, though ;-)

Try this:

my_fruit = [dict(zip(my_fruit, my_fruit))]
Related