[Tutor] passing dictionaries through a file

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Mar 17 01:03:21 CET 2015


On 16 March 2015 at 20:39, Doug Basberg <dbasberg at comcast.net> wrote:
>
> I would like to pass the contents of a dictionary from one program to
> another through a file.  So, what is the elegant way to pass a dictionary by
> file?  My early learning about Python seems to indicate that only ascii is
> easily passed in files.  I am using Python 2.7.4 now.  Should I be learning
> one of the serialization methods?  Can I use ascii in the file and easily
> put that back into a dictionary in the file read program?
>
> I will be very happy to hear alternatives that I can read about and learn
> more about Python.  In C++, I was very happy using structs and classes with
> serialization.  Is the Python solution somewhat similar to C++?

I assume that when you say "dictionary" you mean a dict object. The
best way does depend on what kind of objects are used as the keys and
values of the dict. Assuming that the keys are strings and that the
values are relatively simple objects like strings and integers or
lists of strings etc. then you should be able to use the json module
to export the dict in json format. This format looks similar to the
Python code for creating a dict and can be read into programs written
in many different languages (not just Python).

Here's a simple example:

>>> d = {'asd': 123, 'qwe': 456}

>>> import json       # Import the json module

json.dumps shows us what the json text for the dict would look like:

>>> json.dumps(d)
'{"qwe": 456, "asd": 123}'

We can save it directly to a file like so:

>>> with open('dict.txt', 'w') as fout:
...     json.dump(d, fout)
...

We can then read it in again in another program with:

>>> with open('dict.txt', 'r') as fin:
...     d2 = json.load(fin)
...
>>> d2
{'qwe': 456, 'asd': 123}

You can read more about Python's json module here:
https://docs.python.org/2/library/json.html


Oscar


More information about the Tutor mailing list