One liner: creating a dictionary from a list with indexes in the form of keys

I want to create a dictionary from this list in only one line. The keys for the dictionary will be indexes, and the values โ€‹โ€‹will be list items. Something like that:

a = [51,27,13,56] #given list d = one-line-statement #one line statement to create dictionary print(d) 

Output:

 {0:51, 1:27, 2:13, 3:56} 

I have no specific requirements as to why I want a single line. I am just learning python and wondering if this is possible.

+58
python dictionary list
May 17 '13 at 11:19
source share
5 answers
 a = [51,27,13,56] b = dict(enumerate(a)) print(b) 

will create

 {0: 51, 1: 27, 2: 13, 3: 56} 

enumerate(sequence, start=0)

Returns an enumeration object. the sequence must be a sequence, an iterator, or another object that supports iteration. The next() iterator method returned by enumerate() returns a tuple containing a counter (from the beginning, which defaults to 0), and the values โ€‹โ€‹obtained from iterating over the sequence:

+109
May 17 '13 at 11:23
source share

With another constructor you have

 a = [51,27,13,56] #given list d={i:x for i,x in enumerate(a)} print(d) 
+18
May 17 '13 at 11:50
source share

Try enumerate : it will return a list (or iterator) of tuples (i, a[i]) from which you can build a dict :

 a = [51,27,13,56] b = dict(enumerate(a)) print b 
+14
May 17 '13 at 11:27
source share
 {x:a[x] for x in range(len(a))} 
+4
May 17 '13 at 15:54
source share

Just use list comprehension.

 a = [51,27,13,56] b = dict( [ ((i,a[i]) for i in range(len(a)) ] ) print b 
+1
Aug 27 '16 at 19:16
source share



All Articles