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

Oren Tirosh oren-py-l at hishome.net
Fri Nov 29 09:19:54 EST 2002


On Fri, Nov 29, 2002 at 07:56:44PM +0800, 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. 
...
> 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?

Many Python programmers use an empty class for this:

class Struct:
    pass

s = Struct()
s.name = "John Doe"
s.phone = "555-5127"
etc. 

It has no predefined structure - you can add any field you like and use
the same class for different types of data. You can delete attributes 
with a del statement (e.g. 'del s.phone') and test for the presence of 
an attribute using hasattr ('if hasattr(s, "fax"):')

	Oren





More information about the Python-list mailing list