Convertir dos listas en un diccionario en Python
Imagina que tienes:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
¿Cuál es la forma más sencilla de producir el siguiente diccionario?
a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
12 answers
Así:
>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print(dictionary)
{'a': 1, 'b': 2, 'c': 3}
Voila: -) El constructor en pares dict
y la función zip
son increíblemente útiles: https://docs.python.org/3/library/functions.html#func-dict
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
2018-02-19 14:22:35
Prueba esto:
>>> import itertools
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> adict = dict(itertools.izip(keys,values))
>>> adict
{'food': 'spam', 'age': 42, 'name': 'Monty'}
En Python 2, también es más económico en el consumo de memoria en comparación con zip
.
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
2017-09-13 11:48:23
Imagina que tienes: {[29]]}
keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam')
¿Cuál es la forma más sencilla de producir el siguiente diccionario ?
dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
Most performant-Python 2.7 and 3, dict comprehension: {[36]]}
Una posible mejora en el uso del constructor dict es usar la sintaxis nativa de una comprensión dict (no una comprensión de lista, como otros lo han puesto erróneamente):
new_dict = {k: v for k, v in zip(keys, values)}
En Python 2, zip
devuelve una lista, para evitar crear una lista innecesaria, use izip
en su lugar (con alias a zip puede reducir los cambios de código cuando se mueve a Python 3).
from itertools import izip as zip
Así que eso es todavía:
new_dict = {k: v for k, v in zip(keys, values)}
Python 2, ideal para
izip
de itertools
se convierte en zip
en Python 3. izip
es mejor que zip para Python 2 (porque evita la creación innecesaria de listas), e ideal para 2.6 o inferior:
from itertools import izip
new_dict = dict(izip(keys, values))
Python 3
En Python 3, zip
se convierte en la misma función que estaba en el módulo itertools
, por lo que es simplemente:
new_dict = dict(zip(keys, values))
Sin embargo, una comprensión dict sería más eficaz (ver revisión de rendimiento al final de esta respuesta).
Resultado para todos los casos:
En todos los casos:
>>> new_dict
{'age': 42, 'name': 'Monty', 'food': 'spam'}
Explicación:
Si miramos la ayuda en dict
vemos que toma una variedad de formas de argumentos:
>>> help(dict)
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
El enfoque óptimo es usar un iterable evitando crear estructuras de datos innecesarias. En Python 2, zip crea una lista:
>>> zip(keys, values)
[('name', 'Monty'), ('age', 42), ('food', 'spam')]
En Python 3, el equivalente sería:
>>> list(zip(keys, values))
[('name', 'Monty'), ('age', 42), ('food', 'spam')]
Y Python 3 zip
simplemente crea un objeto iterable:
>>> zip(keys, values)
<zip object at 0x7f0e2ad029c8>
Dado que queremos evitar crear estructuras de datos innecesarias, generalmente queremos evitar el zip
de Python 2 (ya que crea una lista innecesaria).
Alternativas de menor rendimiento:
Esta es una expresión generadora que se pasa al constructor dict:
generator_expression = ((k, v) for k, v in zip(keys, values))
dict(generator_expression)
O equivalente:
dict((k, v) for k, v in zip(keys, values))
Y esta es una comprensión de lista que se pasa al constructor dict:
dict([(k, v) for k, v in zip(keys, values)])
En los dos primeros casos, se coloca una capa adicional de cómputo no operativo (por lo tanto innecesario) sobre el iterable zip, y en el caso de la comprensión de la lista, se crea innecesariamente una lista adicional. Espero que todos ellos tengan menos rendimiento, y ciertamente no más.
Revisión del desempeño:
En Python 3.4.3 de 64 bits, en Ubuntu 14.04, ordenado de la forma más rápida a más lento:
>>> min(timeit.repeat(lambda: {k: v for k, v in zip(keys, values)}))
0.7836067057214677
>>> min(timeit.repeat(lambda: dict(zip(keys, values))))
1.0321204089559615
>>> min(timeit.repeat(lambda: {keys[i]: values[i] for i in range(len(keys))}))
1.0714934510178864
>>> min(timeit.repeat(lambda: dict([(k, v) for k, v in zip(keys, values)])))
1.6110592018812895
>>> min(timeit.repeat(lambda: dict((k, v) for k, v in zip(keys, values))))
1.7361853648908436
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
2017-06-02 14:16:17
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> dict(zip(keys, values))
{'food': 'spam', 'age': 42, 'name': 'Monty'}
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
2008-10-16 19:09:18
También puedes usar comprensiones de diccionario en Python ≥ 2.7:
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> {k: v for k, v in zip(keys, values)}
{'food': 'spam', 'age': 42, 'name': 'Monty'}
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
2012-06-10 20:03:34
Si necesita transformar claves o valores antes de crear un diccionario, se podría usar una expresión de generador . Ejemplo:
>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3]))
Echa un vistazo Código como un Pythonista: Python Idiomático.
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
2008-10-16 20:45:04
Una forma más natural es usar la comprensión del diccionario
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
dict = {keys[i]: values[i] for i in range(len(keys))}
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-04-13 02:07:00
Con Python 3.x, va para las comprensiones dict
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
dic = {k:v for k,v in zip(keys, values)}
print(dic)
Más sobre comprensiones dict aquí , hay un ejemplo:
>>> print {i : chr(65+i) for i in range(4)}
{0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}
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-25 13:47:03
Para aquellos que necesitan código simple y no están familiarizados con zip
:
List1 = ['This', 'is', 'a', 'list']
List2 = ['Put', 'this', 'into', 'dictionary']
Esto se puede hacer por una línea de código:
d = {List1[n]: List2[n] for n in range(len(List1))}
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-04-28 15:18:00
- 2018-04-18
La mejor solución sigue siendo:
In [92]: keys = ('name', 'age', 'food')
...: values = ('Monty', 42, 'spam')
...:
In [93]: dt = dict(zip(keys, values))
In [94]: dt
Out[94]: {'age': 42, 'food': 'spam', 'name': 'Monty'}
Transponerlo:
lst = [('name', 'Monty'), ('age', 42), ('food', 'spam')]
keys, values = zip(*lst)
In [101]: keys
Out[101]: ('name', 'age', 'food')
In [102]: values
Out[102]: ('Monty', 42, 'spam')
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
2018-04-18 02:41:00
Puede usar este código a continuación:
dict(zip(['name', 'age', 'food'], ['Monty', 42, 'spam']))
Pero asegúrese de que la longitud de las listas sea la misma.si la longitud no es la misma.a continuación, la función zip turncate el más largo.
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
2017-11-16 13:36:39
Método sin función zip
l1 = {1,2,3,4,5}
l2 = {'a','b','c','d','e'}
d1 = {}
for l1_ in l1:
for l2_ in l2:
d1[l1_] = l2_
l2.remove(l2_)
break
print (d1)
{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}
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
2017-05-24 05:47:22