Home > Enterprise >  Python - How to change dictionary value dynamically
Python - How to change dictionary value dynamically

Time:04-11

I am trying to use a dictionary in such a way so that it returns a value dynamically. The following code should print "hello" first, then "world". As of now, it prints "hello" two times. Is there a way for me to use this dictionary dynamically?

val = "hello"
test = {
  "A" : val
}
print(test["A"])
val="world"
print(test["A"])

CodePudding user response:

I am thinking that this is not correct use of dictionaries. Could you please the whole task?

You can also check values and change the dictionary value

val = "hello"
test = {
  "A" : val
}
print(test["A"])
val="world"
if test["A"]!=val: test["A"]=val
print(test["A"])

CodePudding user response:

instead of val="world" use test["A"] = "world"

CodePudding user response:

val = "world" assigns a new string to the variable, but doesn't change the existing string. The dictionary test however keeps the old string value, not a reference to the val variable. You need to use another mutable data structure if you want to update the dictionary like this. Just for illustration, I show how a list would work:

val = ["hello"]
test = { "A" : val }
print(test["A"][0])
val[0] = "world"
print(test["A"][0])

Unlike a string, a list can be updated. test keeps the same (list) value as val (there is only one list in this example), but val is changed internally.

Note that you must not use val = ["world"], as this would again just assign a new list to val, but leave test unchanged, i.e. still refer to the old list containing "hello".

  • Related