tags:

views:

149

answers:

6

Let's say I have the following dictionary in a small application.

dict = {'one': 1, 'two': 2}

What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, but maybe there is an easier way.

I do not need a way to convert it to a string, that I can do. But if there is a built in function that does this for me, I would like to know.

To make it clear, what I would like to write to the file is:

write_to_file("dict = {'one': 1, 'two': 2}")
A: 

use pickle

import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'w')
pickle.dump(dict, file)
file.close()

and to read it again

file = open('dump.txt', 'r')
dict = pickle.load(file)

EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :)

jellybean
That writes the dict, but not the dict's name.
Mike D.
A: 

The default string representation for a dictionary seems to be just right:

>>> a={3: 'foo', 17: 'bar' }
>>> a
{17: 'bar', 3: 'foo'}
>>> print a
{17: 'bar', 3: 'foo'}
>>> print "a=", a
a= {17: 'bar', 3: 'foo'}

Not sure if you can get at the "variable name", since variables in Python are just labels for values. See this question.

unwind
+4  A: 

the repr function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.

>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"

writing to a file is pretty standard stuff, like any other file write:

f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()
Adrien Plisson
You didn't address writing it to a file.
Bryan Oakley
@bryan: i am so sorry, i mistakenly thought that writing to a file was pretty obvious... strangely, that's not the case.
Adrien Plisson
Thanks, I ended up with doing it like this. Writing it to a file wasn't actually an issue.
Orjanp
+4  A: 

You could do:

import inspect

mydict = {'one': 1, 'two': 2}

source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0]
print [x for x in source if x.startswith("mydict = ")]

Also: make sure not to shadow the dict builtin!

ChristopheD
Thanks. I did not think of the shadowing of dict. Have some cleaning to do.
Orjanp
+6  A: 

Is something like this what you're looking for?

def write_vars_to_file(_f, **vars):
    for (name, val) in vars.items():
        _f.write("%s = %s\n" % (name, repr(val)))

Usage:

>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
Mike D.
A: 

Do you just want to know how to write a line to a file? First, you need to open the file:

f = open("filename.txt", 'w')

Then, you need to write the string to the file:

f.write("dict = {'one': 1, 'two': 2}" + '\n')

You can repeat this for each line (the +'\n' adds a newline if you want it).

Finally, you need to close the file:

f.close()

You can also be slightly more clever and use with:

with open("filename.txt", 'w') as f:
   f.write("dict = {'one': 1, 'two': 2}" + '\n')
   ### repeat for all desired lines

This will automatically close the file, even if exceptions are raised.

But I suspect this is not what you are asking...

Andrew Jaffe
You are correct. Writing to a file I can do. :)
Orjanp