105

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.

3
  • 3
    What advantage do you think you'll gain by having this dictionary? Index lookups won't be any faster with a dictionary. Commented May 26, 2013 at 23:40
  • @MartijnPieters: Well, I might need, e.g, this: {[x[0]:51, x[1]:27, x[2]:13, x[3]:56}. Commented Jun 26, 2015 at 17:28
  • 4
    then just use zip(): dict(zip(x, a)). Commented Jun 26, 2015 at 17:40

5 Answers 5

173
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:

1
  • 2
    @jamylak But no need to remove yours. People could have learned about count()...
    – glglgl
    Commented May 17, 2013 at 11:24
68

With another constructor, you have

a = [51,27,13,56]         #given list
d={i:x for i,x in enumerate(a)}
print(d)
3
  • 7
    @StefanoSanfilippo Dict and set comprehensions were backported to Python 2.7. Commented May 17, 2013 at 13:55
  • I stand corrected. Still, remember that this does not apply to previous Python 2 versions. Commented May 17, 2013 at 15:11
  • this answer seems more generic! Commented Jun 9, 2022 at 14:56
22
{x:a[x] for x in range(len(a))}
16

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
3

Simply use list comprehension.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.