Complex Nested Dictionaries

Russell E. Owen no at spam.invalid
Fri Feb 20 14:19:50 EST 2004


In article <40354c35 at news.bmi.net>, "T. Earle" <tnospamwade at bmi.net> 
wrote:

>...
>High Wind Warning --> time1 --> state1 --> zone1, zone2, zone3
>                               |
>                               --> time2 --> state1 --> zone4
>                                              --> state2 --> zone5
>
>Keep in mind, each headline or hazard can have multiple times.  Each time
>will have one or more states with each state containing one or more zones.
>Is there a better way than a dictionary.  As mentioned above, the headline
>or hazard is the key I'll be extracting all the information from.

If you really only want to look up data by headline, then a dictionary 
of dictionaries or nested lists or some other kind of collection is easy 
and should suffice. For instance:
warndict["High Wind Warning"] = (
    (time1, {
        state1: (zone1, zone2, zone3),
        state2: (zone1, zone3),
    }),
    (time2, {...}),
)

However, I suspect you will also want to be able to locate data by 
state, time or zone. If that is true, I really think you should consider 
storing the data in a relational database. It sounds like a perfect 
match to your problem. Python has some nice interfaces to various 
databases (including PostgreSQL and MySQL).

-- Russell

P.S. if you do go with the dictionary, note that it is very easy to make 
a variant dictionary that defines
a[key] = foo
to mean "if list a[key] exists, then append foo to that list, otherwise 
create a new list with foo as its only element" (in fact my RO package 
contains just such a class: RO.Alg.MultiDict -- see <http://www.astro.washington.edu/owen/ROPython.html>)



More information about the Python-list mailing list