Complex Nested Dictionaries

T. Earle tnospamwade at bmi.net
Sat Feb 21 17:38:28 EST 2004


Scot,

I really appreciate your help and code.  It really helps me to understand
the underlying solution to my problem.  I have another question though,
what's the best way to test if the headline already exists?  If it does not,
I need to create it along with the required associated data; however, if it
already exists, I need to test to ensure I'm not already adding data that's
already there (e.g., time and/or state already exists).  Basically, I
envision, if the state already exists all I need to do is add the new zone.
I probably should check to make sure the zone doesn't already exists too.
Any help would be greatly appreciated.  I believe it would be similiar to
what Russell mentioned in his previous responce:

"if list a[key] exists, then append; otherwise, create a new list"

Would it be possible to supply a code snippet of this logic to get me
started?  What are state and time?  Is it possible to use the "key" keyword
on these variables to test for their existence?  I apologize for my lack of
knowledge in this particular realm of programming in Python.  Nested
dictionaries have always given me trouble.

Thanks,

T. Earle

>
> warndict['High Wind Warning'] = {
>      time1: {
>          state1: [zone1, zone2, zone3],
>          state2: [zone1, zone3]},
>      time2: {...},
>      ...}
>
> can be built with something like:
> warndict = {}
> for headline, time, state, zone in somesource:
>      timedict = warndict.setdefault(headline, {})
>      statedict = timedict.setdefault(time, {})
>      stateentry = statedict.setdefault(state, [])
>      stateentry.append(zone)





More information about the Python-list mailing list