简体   繁体   中英

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

I want to take a text file that contains something of the form:

{('q0','a'):('q0','a','R'),
('q0','b'):('q0','a','R'),
('q1',' '):('q1',' ','L')}

and place it into a real dictionary. I've been hacking away at this for hours and have gotten very far. I think the solution is simple but I have found nothing useful on the internet. Any help would be appreciated.

>>> ast.literal_eval('''{('q0','a'):('q0','a','R'),
... ('q0','b'):('q0','a','R'),
... ('q1',' '):('q1',' ','L')}
... ''')
{('q1', ' '): ('q1', ' ', 'L'), ('q0', 'a'): ('q0', 'a', 'R'), ('q0', 'b'):
  ('q0', 'a', 'R')}

If the file contains valid Python code describing a dictionary, just 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, I wouldn't recommend this method of passing information around (between Python programs, say). For that I would use something like pickle, or perhaps json serialization, depending on the exact needs.

Try using exec statement:

>>> d="""{('q0','a'):('q0','a','R'),
... ('q0','b'):('q0','a','R'),
... ('q1',' '):('q1',' ','L')}"""
>>> exec("myDict=%s" % d)
>>> myDict
{('q1', ' '): ('q1', ' ', 'L'), ('q0', 'a'): ('q0', 'a', 'R'), ('q0', 'b'): ('q0
', 'a', 'R')}
>>>

The easy way to do what you want is by using eval statement. However, if the file gets tampered, it may cause security problems. I'd highly reccomend using Pickle to store your dictionaries into a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM