Un liner: crear un diccionario a partir de una lista con índices como claves


Quiero crear un diccionario a partir de una lista dada, en una sola línea. Las claves del diccionario será índices y los valores serán los elementos de la lista. Algo como esto:

a = [51,27,13,56]         #given list

d = one-line-statement    #one line statement to create dictionary

print(d)

Salida:

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

No tengo ningún requisito específico sobre por qué quiero una línea. Estoy explorando Python, y preguntándome si eso es posible.

Author: jamylak, 2013-05-17

5 answers

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

Producirá

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

enumerate(sequence, start=0)

Devuelve un objeto enumerado. sequencedebe ser una secuencia, un iterador , o algún otro objeto que soporte la iteración. El método next() del iterador devuelto por enumerate() devuelve un tuple que contiene un recuento (desde start que por defecto es 0) y los valores obtenidos al iterar sobre sequence:

 129
Author: glglgl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-23 17:57:49

Con otro constructor, tienes

a = [51,27,13,56]         #given list
d={i:x for i,x in enumerate(a)}
print(d)
 27
Author: octoback,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-17 11:50:38

Try enumerate: devolverá una lista (o iterador) de tuplas (i, a[i]), a partir de la cual se puede construir un dict:

a = [51,27,13,56]  
b = dict(enumerate(a))
print b
 14
Author: Stefano Sanfilippo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-17 11:27:16
{x:a[x] for x in range(len(a))}
 8
Author: Emilio M Bumachar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-17 15:54:02

Simplemente use comprensión de lista.

a = [51,27,13,56]  
b = dict( [ ((i,a[i]) for i in range(len(a)) ] )
print b
 1
Author: Shahrukh khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-27 19:16:26