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.

Answers


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.


>>> 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')}

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.


Need Your Help

Apache spark on eclipse

java eclipse hadoop apache-spark

The question I asked was marked as too broad. After searching around more I got my basics more clear. So hopefully I will be much more specific now.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.