complex data types?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Sep 18 07:27:38 CEST 2005


On Sat, 17 Sep 2005 20:49:32 -0500, richard wrote:

> I'd like to have an array in which the elements are various data types. 
> How do I do this in Python?  
> 
> For example:
> 
> array[0].artist = 'genesis'
> array[0].album = 'foxtrot'
> array[0].songs = ['watcher', 'time table', 'friday']
> array[1].artist = 'beatles'
> array[1].album = 'abbey road'
> array[1].songs = ['come', 'something', 'maxwell']
>     	
> Everything I try generates errors or results in array[0].songs equaling 
> array[1].songs. I feel I'm missing something obvious.

Would you like to tell us what you have already tried, or should we guess?

To get good answers, it helps to ask good questions. What have you tried.
What errors did you generate? Most importantly, what are you hoping to do
with your data structure after you've got it?

One hint is to split the problem into two halves, then solve each one. It
looks to me like you are trying to store a list of albums. So half the
problem is solved: the list of albums is just a list. Each item is an
album. Now you just have to decide on how you store each album. Here is
one solution:

# Create a single album.
album = {"artist": "beetles", "title": "abbey road", \
    "songlist" = ['come together', 'something', 'maxwell']}

# Store it in the album list.
albums.append(album)

You can change an item like this:

# Oops, wrong artist...
albums[0]["artist"] = "beatles"
albums[0]["songlist"].append("mean mr mustard")

Does this solution work for you? If not, what does it not do that you need
it to do?


-- 
Steven.




More information about the Python-list mailing list