loading dictionary from a file
Ben Finney
bignose+hates-spam at benfinney.id.au
Wed Feb 6 20:33:46 EST 2008
Amit Gupta <emailamit at gmail.com> writes:
> Need a python trick, if it exists:
>
> I have a file that stores key, value in following format
> --
> "v1" : "k1",
> "v2" : "k2"
> --
>
> Is there a way to directly load this file as dictionary in python.
That input looks almost like valid JSON <URL:http://json.org/>.
If you can easily massage it into JSON format, you can use the Python
JSON library <URL:http://cheeseshop.python.org/pypi/python-json>:
import json
input_text = open('foo.txt').read()
input_json = "{%(input_text)s}" % vars()
reader = json.JsonReader()
data = reader.read(input_json)
If the 'input_json' above actually is valid JSON, that will give the
corresponding Python data object.
This avoids the massive security hole of performing 'eval' on
arbitrary user input; the input isn't executed, merely parsed (as
JSON) to create a data object.
--
\ “I busted a mirror and got seven years bad luck, but my lawyer |
`\ thinks he can get me five.” —Steven Wright |
_o__) |
Ben Finney
More information about the Python-list
mailing list