<html>
<head>
<style><!--
.hmmessage P
{
margin:0px;
padding:0px
}
body.hmmessage
{
font-size: 12pt;
font-family:Calibri
}
--></style></head>
<body class='hmmessage'><div dir='ltr'><br><br><div>> From: steve+comp.lang.python@pearwood.info<br>> Subject: Re: Beginner question<br>> Date: Tue, 4 Jun 2013 12:35:59 +0000<br>> To: python-list@python.org<br>> <br>> On Tue, 04 Jun 2013 14:23:39 +0300, Carlos Nepomuceno wrote:<br>> <br>> > Started answering... now I'm asking! lol<br>> > <br>> > I've tried to use dict() to create a dictionary to use like the switch<br>> > statement providing variable names instead of literals, such as:<br>> > <br>> >>>> a='A'<br>> >>>> b='B'<br>> >>>> {a:0,b:1} #here the variables are resolved<br>> > {'A': 0, 'B': 1}<br>> > <br>> > That's ok! But if I use dict() declaration:<br>> > <br>> >>>> dict(a=0,b=1)<br>> > {'a': 0, 'b': 1} #here variable names are taken as literals<br>> > <br>> > What's going on? Is there a way to make dict() to resolve the variables?<br>> <br>> <br>> This is by design. You're calling a function, dict(), and like all <br>> functions, code like:<br>> <br>> func(name=value)<br>> <br>> provides a *keyword argument*, where the argument is called "name" and <br>> the argument's value is as given. dict is no different from any other <br>> function, it has no superpowers, keyword arguments are still keyword <br>> arguments.<br>> <br>> In this case, there is no simple way to use the dict() function[1] the <br>> way you want. You could build up a string and then call eval():<br>> <br>> s = "dict(%s=0, %s=1)" % (a, b)<br>> d = eval(s)<br>> <br>> but that's slow and inconvenient and dangerous if your data is untrusted.<br>> <br>> So in this specific case, you should stick to the {} method.<br>> <br>> <br>> <br>> [1] Technically it's a type, not a function, but the difference makes no <br>> difference here.<br>> <br>> -- <br>> Steven<br><br>It's superclear now! You're an excelent teacher!<br><br>Can you explain me the difference of the type and function you've just mentioned?<br><br></div> </div></body>
</html>