Newbie Question: Giving names to Elements of List/Tuple/Dict

Mikael Olofsson mikael at isy.liu.se
Fri Nov 29 07:15:40 EST 2002


Hi Alfredo!

On 29 Nov 2002 19:56:44 +0800
"Alfredo P. Ricafort" <alpot at mylinuxsite.com> wrote:
> I'm quite new to Python.  So far I find it to be easy to learn and
> simple to program.  However, one thing that I missed, especially
> someone coming from C language, is 'struct'. It seems that when you
> define a data structure in the form of a List, Tuple, or Dict., there
> is no way to give names to each element. 
>
> [snip C code]
> 
> Now my problem is that when the structure of the record change, your
> index has to change also. So in the example above, when the 'Name'
> element is moved(say as the 3rd element - Customer[i][2]), then you
> have to look all over your code and change accordingly. 
> 
> My question now is, how can I assign names to the elements? Or is
> there a better way of doing this?

I know close to nothing about C, but based on your description, you
should take a look at dictionaries. Then you can do the following:

    Customer=[ 
        {'Name': name1,'Address': address1,'TelNo': telno1},
        {'Name': name2,'Address': address2,'TelNo': telno2}
        ]

The name of the first customer is then given by

    Customer[0]['Name']

...or you can create your own class if you really want flexibility.

HTH
/Mikael

-----------------------------------------------------------------------
E-Mail:  mikael at isy.liu.se
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael               
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339

         /"\
         \ /     ASCII Ribbon Campaign
          X      Against HTML Mail
         / \

This message was sent by Sylpheed.
-----------------------------------------------------------------------
Linköpings kammarkör: www.kammarkoren.com




More information about the Python-list mailing list