I am trying to parse a string to separate the lists within the string. I currently have the string:
string = "[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]"
Is there any way to parse string so that the dictionary key is the first element of the list and the value of the key is the next to elements. For example:
{'q1': ('0','q1'), 'q1': ('1','q2'), 'q2': ('0','q2'), 'q2': ('1', 'q1')}
Insted of dictionary you can have list:
you can use ast.literal_eval to parse python data structure from string
>>> import ast
>>> my_string = "[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]"
>>> k = ast.literal_eval(my_string)
>>> k
[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]
>>> [[x[0],tuple(x[1:])] for x in k]
[['q1', ('0', 'q1')], ['q1', ('1', 'q2')], ['q2', ('0', 'q2')], ['q2', ('1', 'q1')]]
You can use JSON but the string format has to be a dict and you cannot have 2 times the same key:
import json
string ='{"q": ["0", "q1"], "q1": ["1", "q2"], "q3": ["1", "q1"], "q2": ["0", "q2"]}'
dict = json.loads(string)
print dict
Output: {'q': ['0', 'q1'], 'q1': ['1', 'q2'], 'q3': ['1', 'q1'], 'q2': ['0', 'q2']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With