Python Create Dynamic Variables

To create a dynamic variable name in Python use a dictionary. A dictionary in Python contains key/value pairs that can be of various data types.

 

The key will act as the variable name and the value as the variable value. To demonstrate this, let's create a dynamic variable using a dictionary and access its value.

 

name = 'first'
value = 29

dynamic_var = {name: value}

print(dynamic_var[name])
29

 

In the example above, the name and value of the variable to create are defined then they are added to a dictionary as a key/value pair. Then the value of the variable can be access by passing its name inside [] (square brackets).