1

How to assign variable names programmatically in python?

I have a lot of objects and their names are not predefined. Currently I am reading in from a file which has names in it and I’m reading in them into a list. But from this list how do I assign the names to the variables so that variables are easy to remember and work with. I cannot hard code because :

a. I don’t want them to be fixed

b. I have a lot of names so it is not feasible to type in. (Even copy paste every name)

  • use `dict` to create a key-value (name and values)? – DirtyBit Jun 16 '20 at 23:02
  • 1
    **Don't use dynamic variables**. Use a *container* like a list or a dict. – juanpa.arrivillaga Jun 16 '20 at 23:05
  • Thanks @juanpa.arrivillaga just curious if it is possible or not –  Jun 16 '20 at 23:08
  • @delmiaa in CPython, you can directly modify the global scope using the global namespace, `globals()` which is *literally* a `dict` object. However, modifications to local namespace returned by `locals()` will not be reflected. Basically, local namespaces are "read only" programatically... this is due to an optimization that makes local name access quite fast (not requiring a hash-lookup but merely indexing into an array). However, this local namespace array can't be modified at runtime (in any *sane* way.. ) – juanpa.arrivillaga Jun 16 '20 at 23:13

1 Answers1

2

Use dictionaries. (And assign its keys programmatically!)

You can assign the variables names which you’ve already read into the list and then have their values read. I’m still not clear about how you want your values but assuming you have them in a list too as you have your variable names, then just zip both lists as dict:

data = dict(zip(names, values))

Now you can access each variable by its name as follows:

data['name']
Hamza
  • 5,373
  • 3
  • 28
  • 43