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

Time:10-09

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?

CodePudding user response:

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.

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.

CodePudding user response:

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.

CodePudding user response:

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

Dict.update({Var1: Var2})
  • Related