[pyar] ¿Este es el comportamiento esperado de dict()?

Ramiro Morales cramm0 en gmail.com
Mie Nov 4 21:27:53 ART 2015


2015-11-04 21:14 GMT-03:00 Manuel Kaufmann <humitos en gmail.com>:
> Hola,
>
> Me acabo de encontrar con una situación interesante:
>
> Python 3.4.3 (default, Oct 14 2015, 20:28:29)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> d = {1: 'key number'}
>>>> dict(key='content data', **d)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: keyword arguments must be strings
>>>> d = {'1': 'key number'}
>>>> dict(key='content data', **d)
> {'1': 'key number', 'key': 'content data'}
>>>>
>
> ¿Creen que es correcto este comportamiento?
>
> ¿Porqué no puedo tener llaves numéricas en "d" y usarlo así "**d" en dict?
>

S lo que queres hacer es lo que creo que queres hacer, no hace falta
que 'desempaquetes' d cuando se lo pasás a dict(). pero hay que tener
cuidado con el orden de los parámetros (ver doc de dict())


 ~  ipython
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: d = {1: 'key number'}

In [2]: dict(key='content data', d)
  File "<ipython-input-2-3d8570c98118>", line 1
    dict(key='content data', d)
SyntaxError: non-keyword arg after keyword arg


In [3]: dict(d, key='content data')
Out[3]: {1: 'key number', 'key': 'content data'}

-- 
Ramiro Morales
@ramiromorales


More information about the pyar mailing list