[Tutor] generate a list/dict with a dynamic name..

Danny Yoo dyoo at hashcollision.org
Sun Sep 27 20:31:40 CEST 2015


On Sun, Sep 27, 2015 at 9:38 AM, bruce <badouglas at gmail.com> wrote:
> Hi.
>
> I can do a basic
>  a=[]
> to generate a simple list..
>
> i can do a a="aa"+bb"
>
> how can i do a
>  a=[]
>
> where a would have the value of "aabb"
>
> in other words, generate a list/dict with a dynamically generated name


There is a conceptual split we make about things that are are "static"
(constant throughout time), and other things should be "dynamic"
(possibly changing throughout time).

In modern programming style, most people prefer that the program text
itself be static, but the *data* in the program may be dynamic.  (This
preference toward static program text has not always been true, nor is
it universally true.  Self-modifying programs do exist.  A modern
example, for example, are Just-In-Time systems, where the program text
is reconstructed on-the-fly in response to the current execution of a
program.)

In general, most programming systems you'll see will strongly prefer
that the program text be static, because static systems are easier to
understand: their meaning doesn't change over time nor does it depend
on the circumstances of the outside world.

This being said, the preference for static program text doesn't mean
we can't handle dynamically generated names.  We can place the
dynamism in the *data structures* that our programs handle, rather
than in the program text itself.  A dictionary is a data structure
that can associate names to values, and that's a common tool we use to
do what you're asking.


For example:

######
my_dict = {}
my_dict['aabb'] = []
######

Here, the name 'aabb' is static: it's part of the program text.

But the names we add to a dictionary don't always have to be static.
A dictionary, in particular, allows those names to be dynamically
determined.  If we are using Python 3, the following snippet will show
this in action:

#######
my_dict = {}
name = input('Please enter a name: ')
my_dict[name] = []
#######

and if we are using Python 2, do this instead:

#######
my_dict = {}
name = raw_input('Please enter a name: ')
my_dict[name] = []
#######


More information about the Tutor mailing list