Beginner question
Fábio Santos
fabiosantosart at gmail.com
Tue Jun 4 07:34:26 EDT 2013
On 4 Jun 2013 12:28, "Carlos Nepomuceno" <carlosnepomuceno at outlook.com>
wrote:
>
> Started answering... now I'm asking! lol
>
> I've tried to use dict() to create a dictionary to use like the switch
statement providing variable names instead of literals, such as:
>
> >>> a='A'
> >>> b='B'
> >>> {a:0,b:1} #here the variables are resolved
> {'A': 0, 'B': 1}
>
> That's ok! But if I use dict() declaration:
>
> >>> dict(a=0,b=1)
> {'a': 0, 'b': 1} #here variable names are taken as literals
>
> What's going on? Is there a way to make dict() to resolve the variables?
Well yes.
dict(**{a:0,b:1})
The dict() constructor makes a dictionary from keyword arguments. So you
just have to feed it keyword arguments using **.
And if you're in a bad day,
dict(**locals())
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130604/1ca65eef/attachment.html>
More information about the Python-list
mailing list