python – How to dynamically create a variable whose name may contain the value of another variable?

Question:

You need to create a variable like this (pseudocode):

Имя_%номер-пользователя% = значение

How to do this?

Answer:

In addition to the existing answer.

Dynamic creation of variables is difficult to maintain. And it might not be safe.

You can use dictionaries. Dictionaries are stores of keys and values.

>>> dct = {'x': 1, 'y': 2, 'z': 3}
>>> dct
{'y': 2, 'x': 1, 'z': 3}
>>> dct["y"]

You can also use key names as variables

>>> x = "spam"
>>> z = {x: "eggs"}
>>> z["spam"]
'eggs'

For times when you think of something like

var1 = 'foo'
var2 = 'bar'
var3 = 'baz'
...

a list might be more appropriate than a dictionary. A list is an ordered sequence of objects with integer indices:

l = ['foo', 'bar', 'baz']
print(l[1])           # prints bar, because indices start at 0
l.append('potatoes')  # l is now ['foo', 'bar', 'baz', 'potatoes']

Lists can be more convenient than dictionaries with integer keys. For example, adding and removing elements is more convenient.

Scroll to Top