How do I update a dictionary where the key is a variable?

Question:

I am trying to update a dictionary using dict.update() where the key name is a variable, like so:

Dict = {}
Var1 = 1
Var2 = 2

Dict.update(Var1=Var2)
print(Dict)

However, this outputs:

{‘Var1’: 2}

Instead of what I need, which is:

{1:2}

This is not my code just a similar example, but is there any way to make it read the variable as a variable instead of as a string?

Asked By: Kian Murray

||

Answers:

When you use update like this, you are using keyword arguments, where you can pass parameters by name instead of by position in the list of arguments. The keyword in such arguments is treated as a name; the only way to have a variable keyword is to use the **kwargs syntax to pass an entire dict as a set of key=value parameters. That means that this would work . . .

update = { Var1: Var2 }
Dict.update(**update)

. . . except that keywords have to be strings, not numbers; trying to use your Var1 with value 1 as a keyword triggers a TypeError.

Because dict.update is designed for updating a dictionary, however, it also accepts an actual dictionary as an argument, without conversion to keyword arguments via **. So this does work:

Dict.update({ Var1: Var2 })

But you don’t need update or its keyword arguments in your case; you can just use assignment instead:

Dict[Var1] = Var2

A couple style things: don’t name variables with capital letters; that is usually an indication that a value is a constant. Also, don’t use "Dict" as a variable name. Such names risk shadowing builtin functions, since functions and variables share the same namespace in Python. For example, if you assign a value to dict, you’ve just removed your pointer to the dict global function.

Answered By: Mark Reed

Just this:

Dict[var1] = var2

Calling "update" is a different thing: it can update several keys at once, and it is more usually called with another dictionary passed as positional parameter. In the form .update(par_name=value) the left part is used by the language as a "named parameter" and it is fixed in code, as a literal.

Answered By: jsbueno

In addition to both existing answers, you could do the following if you’d prefer to use update:

Dict.update({Var1: Var2})
Answered By: Inertial Ignorance
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.