Beginner question

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jun 4 08:35:59 EDT 2013


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



More information about the Python-list mailing list