faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 6 people (50%) answered Yes
Recently 2 of 5 people (40%) answered Yes

Entry

Writeable dictionary

Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 169, Python Snippet Support Team


"""
Packages: basic_datatypes.dictionaries
"""
# writeabledict.py
"""A writeable dictionary."""
from UserDict import UserDict
class WriteableDict(UserDict):
    def __init__(self, other=None):
        """Provides copy-constructor."""
        UserDict.__init__(self)
        if type(other) == type({}):
            self.data = other.copy()
        elif isinstance(other, UserDict):
            self.data = other.data.copy()
    def write(self, filename, dictname="data"):
        if not filename[-3:] == ".py":
            filename = filename + ".py" # duh!
        f = open(filename, "w")
        f.write("# %s generated by writeabledict.py\n\n" % filename)
        f.write("%s = {\n" % dictname)
        for key in self.data.keys():
            f.write("\t%s: %s,\n" % (repr(key), repr(self.data[key])))
        f.write("}\n")
        f.close()
if __name__ == "__main__":
    telnr = WriteableDict()
    telnr['hans'] = 4540
    telnr['huub'] = 4774
    telnr['uszo'] = [telnr['huub'], telnr['hans']]
    telnr['misc'] = {'fred': 3456, 'jaap': 9233, 'rik': 4521}
    print telnr
    telnr.write("telnrdict.py")
    import telnrdict
    print telnrdict.data