One liner: creating a dictionary from list with indices as keys

PythonListDictionaryPython 3.x

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

a = [51,27,13,56]
b = dict(enumerate(a))
print(b)

will produce

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

> enumerate(sequence, start=0)

> 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 by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

Solution 2 - Python

With another constructor, you have

a = [51,27,13,56]         #given list
d={i:x for i,x in enumerate(a)}
print(d)

Solution 3 - Python

{x:a[x] for x in range(len(a))}

Solution 4 - Python

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

Solution 5 - Python

Simply use list comprehension.

a = [51,27,13,56]  
b = dict( [ (i,a[i]) for i in range(len(a)) ] )
print b

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNawazView Question on Stackoverflow
Solution 1 - PythonglglglView Answer on Stackoverflow
Solution 2 - PythonkiriloffView Answer on Stackoverflow
Solution 3 - PythonEmilio M BumacharView Answer on Stackoverflow
Solution 4 - PythonStefano SanfilippoView Answer on Stackoverflow
Solution 5 - PythonShahrukh khanView Answer on Stackoverflow