[Tutor] how do (or do I) do a list of variable names?

Peter Otten __peter__ at web.de
Sun Feb 2 14:19:44 CET 2014


rick wrote:

> Hello Everyone,
> 
> I think my approach is all wrong, but here goes.
> 
> var1 = []; var2 = []; var3 = [];  . . .  ~50 lists
> 
> 
> each variable would be a list of two digit integers, or two digit
> integers stored as strings (I don't need to do any math, I just need to
> know which integers are in which variable)
> 
> container = [var1,var2,var3 . . . ]
> 
> I'd like to be able to iterate over container or pick out one or more of
> my lists to write out an input (text) file for an external program.
> 
> The thing is, assigning all those lists to a list gives me a list of
> lists, not a list of my variable names.  Worse, I may or may not be able
> to have changes to a list show up in my list of lists, depending on how
> & when I do it.
> 
> Really kludgy, but it is a one off that will likely never be used again.

You typically don't make 50 variables in Python, you use a dict:

>>> container = {
...     "foo": [10, 20],
...     "bar": [30, 40],
...     "baz": [40, 50],
...     #...
... }

you can then look up the "foo" list with

>>> print(container["foo"])
[10, 20]

If you want to know all the keys that 40 is associated with you can either 
iterate through the items every time

>>> print([k for k, v in container.items() if 40 in v])
['bar', 'baz']

or build the reverse dict once

>>> for k, values in container.items():
...     for v in values:
...             value_to_key.setdefault(v, set()).add(k)
... 

and then profit from fast lookup

>>> print(value_to_key[40])
{'bar', 'baz'}
>>> print(value_to_key[10])
{'foo'}

until you make changes to the original `container` dict.



More information about the Tutor mailing list