Dictionary from a file

Hans Nowak hnowak at cuci.nl
Mon Jan 24 16:13:02 EST 2000


On 23 Jan 00, at 22:27, Peter Schopfer (aka Dr. J. -  wrote:

> Hello
> 
> I have a dictionary that is too big to fit right in my program, so i was
> going to have it as a seperat file, labeled dic.py. how would i be able to
> retrieve this dictionary. wuld this work:
> 
> from dic.py import dictionary
> mydic=dic.dictionary
> 
> i am a newbie, so any help would be appreciated
> thanks

See my snippets page (http://tor.dhs.org/~zephyrfalcon/snippets), snippet 
#169, for an example. 

I uploaded some new stuff yesterday and I'm not sure yet if everything 
works as it should, so I'll copy & paste the example for you:

---begin code-----

# 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

---end code---

The WriteableDict class writes a dictionary to a Python file, which can be 
imported, as you can see in the last two lines.

Alternatively, you could take repr(dict), which is a string, and write it 
to a file. You can read it again by reading the string and using eval() on 
it. (Didn't test this though)

Hope this helps,


--Hans Nowak (zephyrfalcon at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
You call me a masterless man. You are wrong. I am my own master.




More information about the Python-list mailing list