Nawaz Nawaz - 1 year ago 77
Python Question

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

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



{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.

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

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download