[Tutor] Lists in lists

Brian van den Broek broek at cc.umanitoba.ca
Sun Sep 17 21:55:47 CEST 2006


Kent Johnson said unto the world upon 16/09/06 07:49 PM:
> Brian van den Broek wrote:
>> Kent Johnson said unto the world upon 16/09/06 04:35 PM:
>>> Brian van den Broek wrote:
> 
>>>> You say you are new to Python. Well, it might not now be obvious why 
>>>> dictionaries are especially useful, but they are *central* to the 
>>>> pythonic approach. The sooner you become comfortable with them, the 
>>>> better (IMHO).
>>> I agree that dicts are extremely useful, but I don't think they add 
>>> anything in this case unless there is actually a need for keyed 
>>> access. A list of lists (or tuples) seems very appropriate to me. A 
>>> good alternative might be a list of Bunches.
>>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308
>>>
>>> Kent
>>
>>
>> Hi Kent and all,
>>
>> I should have included the reason why I thought a dict might be better 
>> here. (I did send it in a private email after the post.)
>>
>> A lot of ways I could imagine the time-line data being used might 
>> involve wanting to access some one year, rather than the entire 
>> time-line.
> 
> Yes, I was a bit hasty in denouncing dicts, the best data structure does 
> depend entirely on how it is to be used, and we don't know enough about 
> this application to know.



Hi Kent and all,

I absolutely agree that my suggestions did get a bit ahead of the spec :-)

A combination of thinking about what *I* would want a yearly headline 
program to do and wanting to encourage comfort with dicts ASAP is what 
drove the suggestion. But, if the OP has a simpler spec than my 
imaginary one . . . .


>>  >>> print timeline_data[800][0]
>>
>> seems *way* better than something like:
>>
>>  >>> for year_data in timeline_data_as_list_of_lists:
>> ...    if year_data[0] == 800:
>> ...       print year_data[1]
>> ...       break
>>
>> which would be what the original list structure seems to require.
> 
> The thing is, though, how will you know that 800 is a valid year? You 
> need a list of valid years. If you get that list from the dict keys, and 
> iterate that, you haven't really gained anything over a list of tuples. 
> Maybe you have a lot of items and the user enters a year and you want to 
> print out the data you have on the year...

def print_year_headline(year):
     try:
         print timeline_data[year][0]
     except KeyError:
         print "I am sorry; we have no data on year %s." %year

allows for random access by year while handling the problem.

But Kent's point about not getting too far ahead of the spec is surely 
right.

To the OP: if Kent and I disagree, there are very good odds that 
Kent's the one to listen to ;-)

Best to all,

Brian vdB


More information about the Tutor mailing list