开发者

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

开发者 https://www.devze.com 2023-01-28 14:10 出处:网络
I want to take a text file that contains something of the form: {(\'q0\',\'a\'):(\'q0\',\'a\',\'R\'), (\'q0\',\'b\'):(\'q0\',\'a\',\'R\'),

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消