parsing - How do I parse a text file in dictionary form and put it into a dictionary in python? -


i want take text file contains of form:

{('q0','a'):('q0','a','r'), ('q0','b'):('q0','a','r'), ('q1',' '):('q1',' ','l')} 

and place real dictionary. i've been hacking away @ hours , have gotten far. think solution simple have found nothing useful on internet. appreciated.

if file contains valid python code describing dictionary, use eval:

>>> value = "{('q0','a'):('q0','a','r'),('q0','b'):('q0','a','r'),('q1',' '):('q1',' ','l')}" >>> value "{('q0','a'):('q0','a','r'),('q0','b'):('q0','a','r'),('q1',' '):('q1',' ','l')}" >>> d = eval(value) >>> type(d) <type 'dict'> >>> d {('q1', ' '): ('q1', ' ', 'l'), ('q0', 'a'): ('q0', 'a', 'r'), ('q0', 'b'): ('q0', 'a', 'r')} 

however, wouldn't recommend method of passing information around (between python programs, say). use pickle, or perhaps json serialization, depending on exact needs.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -