Python: Parsing a complex string into usable data for analysis
Question: Is it possible to parse the below string, using Python, or convert it into
another data structure so that each element can be accessed for analysis?

This is an example line from a large text file where each line has the same
format.

    
    
    string = ["('a', '1')", "('b', '2')"]
    


Answer: If you simply want to convert the tuple-strings to tuples, you can use
[`ast.literal_eval`](https://docs.python.org/2/library/ast.html#ast.literal_eval):

    
    
    >>> import ast
    >>> [ast.literal_eval(x) for x in string]
    [('a', '1'), ('b', '2')]
    

Use of `ast.literal_eval` rather than `eval` is encouraged as it is considered
safer: it does not execute _all_ strings of Python code, only literal
expressions (no variables, no function calls).

You can then access the elements of the tuples using Python's slice/index
notation, or convert to an alternative data structure, e.g. a dictionary:

    
    
    >>> dict([ast.literal_eval(x) for x in string])
    {'a': '1', 'b': '2'}
    

