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

Freddie freddie at madcowdisease.org
Fri Nov 29 08:45:17 EST 2002


Alfredo P. Ricafort wrote:

> Hi,
>
> 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.
>
> For example:
>
> In C:
>    struct Customer {
>           char * Name;
>           char * Address;
>           char * TelNo;
>    } Customer[];
>
>    printf("Customer Name is %s\n",Customer[i].Name);
>
>
> In Python:
>    Customer=[ [Name,Addres,TelNo], [Name,Address,TelNo],.....]
>
>    print "Customer Name is %" Customer[i][0]
>
> 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?
>
> Thanks.
>
> AL
>
You could use a dictionary, like so:

cust = {}
cust['Name'] = 'Bob'
cust['Address'] = '12 Bob St'
cust['TelNo'] = '555-EAT-BEEF'

or even just:

cust = { 'Name': 'Bob', 'Address': '12 Bob St', 'TelNo': '555-EAT-BEEF' }


If you're really bored, you could make a simple class for it:

class Entry:
     def __init__(self, name, address, telno):
         self.Name = name
         self.Address = address
         self.TelNo = telno

cust = Entry('Bob', '12 Bob St', '555-EAT-BEEF')

Then you can access each part as cust.Name, cust.Address, or cust.TelNo. 
Exciting stuff :)

Freddie




More information about the Python-list mailing list