python - How do I create a variable number of variables? -
how accomplish variable variables in python?
here elaborative manual entry, instance: variable variables
i have heard bad idea in general though, , security hole in python. true?
you can use dictionaries accomplish this. dictionaries stores of keys , values.
>>> dct = {'x': 1, 'y': 2, 'z': 3} >>> dct {'y': 2, 'x': 1, 'z': 3} >>> dct["y"] 2
you can use variable key names achieve effect of variable variables without security risk.
>>> x = "spam" >>> z = {x: "eggs"} >>> z["spam"] 'eggs'
for cases you're thinking of doing like
var1 = 'foo' var2 = 'bar' var3 = 'baz' ...
a list may more appropriate dict. list represents ordered sequence of objects, integer indices:
l = ['foo', 'bar', 'baz'] print(l[1]) # prints bar, because indices start @ 0 l.append('potatoes') # l ['foo', 'bar', 'baz', 'potatoes']
for ordered sequences, lists more convenient dicts integer keys, because lists support iteration in index order, slicing, append
, , other operations require awkward key management dict.
Comments
Post a Comment