Beginner question

Carlos Nepomuceno carlosnepomuceno at outlook.com
Tue Jun 4 08:51:38 EDT 2013



> From: steve+comp.lang.python at pearwood.info
> Subject: Re: Beginner question
> Date: Tue, 4 Jun 2013 12:35:59 +0000
> To: python-list at python.org
> 
> On Tue, 04 Jun 2013 14:23:39 +0300, Carlos Nepomuceno 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?
> 
> 
> This is by design. You're calling a function, dict(), and like all 
> functions, code like:
> 
> func(name=value)
> 
> provides a *keyword argument*, where the argument is called "name" and 
> the argument's value is as given. dict is no different from any other 
> function, it has no superpowers, keyword arguments are still keyword 
> arguments.
> 
> In this case, there is no simple way to use the dict() function[1] the 
> way you want. You could build up a string and then call eval():
> 
> s = "dict(%s=0, %s=1)" % (a, b)
> d = eval(s)
> 
> but that's slow and inconvenient and dangerous if your data is untrusted.
> 
> So in this specific case, you should stick to the {} method.
> 
> 
> 
> [1] Technically it's a type, not a function, but the difference makes no 
> difference here.
> 
> -- 
> Steven

It's superclear now! You're an excelent teacher!

Can you explain me the difference of the type and function you've just mentioned?

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130604/f2b8b30e/attachment.html>


More information about the Python-list mailing list