How do I create a dict from a list in {index: value} format?

Let's assume this list:

a = [0.41   1.87  1.10  7.05]

      

I would like to build a dict that looks like this:

d = {0: 0.41, 1: 1.87, 2: 1.10, 3: 7.05}

      

There are many answers on SO about how to convert from a list to a dict, however I could not find one that addresses this specific need (i.e. the dict's key value is the index of the item in the list).

I can create images, these are cumbersome ways to do it using a loop for

, getting a.index(i)

, adding, encrypting, etc., but I'm wondering if I'm missing a more efficient way to create this dictionary.

+3


source to share


2 answers


You can use dict comprehension for this purpose!



>>> d= [0.41,1.87,1.10,7.05]
>>> {index:i for index,i in enumerate(d)}
{0: 0.41, 1: 1.87, 2: 1.1, 3: 7.05}

      

+5


source


Simple way:



>>> d = [0.41, 1.87, 1.10, 7.05]
>>> dict(enumerate(d))
{0: 0.41, 1: 1.87, 2: 1.1, 3: 7.05}

      

+3


source







All Articles