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

400 Bad Request on Apache/PHP AddHandler wrapper -

Add email recipient to all new Trac tickets -

php - Change action and image src url's with jQuery -