I want to create a dictionary out of a given list, in just one line. The keys of the dictionary will be indices, and values will be the elements of the list. Something like this:
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 don’t have any specific requirements as to why I want one line. I’m just exploring python, and wondering if that is possible.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
a = [51,27,13,56] b = dict(enumerate(a)) print(b)
will produce
{0: 51, 1: 27, 2: 13, 3: 56}
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The
next()method of the iterator returned byenumerate()returns atuplecontaining a count (from start which defaults to 0) and the values obtained from iterating over sequence:
Method 2
With another constructor, you have
a = [51,27,13,56] #given list
d={i:x for i,x in enumerate(a)}
print(d)
Method 3
{x:a[x] for x in range(len(a))}
Method 4
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
Method 5
Simply use list comprehension.
a = [51,27,13,56] b = dict( [ (i,a[i]) for i in range(len(a)) ] ) print b
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0