How to implement 2-D array using UserDict?

Courageous jkraska1 at san.rr.com
Thu Aug 3 00:29:58 EDT 2000


Sam Wun wrote:
> 
> I want to do something like:
> 
> import UserDict
> dict = UserDict.UserDict()
> dict["Section"]["key"] = "some value"
> 
> How can I do that in Python?

Since you did not explain your desire to do this with UserDict,
as opposed to plain ole' python dictionaries, I'll answer with
plain ole' python dictionaries:

#test.py:

dict = {}

def addentry ( key1, key2, value ):

    global dict

    if dict.has_key(key1):
        
        bucket = dict[key1]
        bucket[key2]=value

    else:

        bucket = {}
        bucket[key2]=value
        dict[key1]=bucket

def test():
    
    addentry ( "sec1", "fred", 1 )
    addentry ( "sec1", "nancy", 8 )
    addentry ( "sec2", "jim", 7 )
    addentry ( "sec2", "jen", 2 )

    print `dict`

test()

---------------------

{'sec2': {'jim': 7, 'jen': 2}, 'sec1': {'fred': 1, 'nancy': 8}}



More information about the Python-list mailing list