Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse a string into a dictionary

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')}
like image 233
user3246978 Avatar asked Sep 15 '26 15:09

user3246978


2 Answers

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')]]
like image 82
Hackaholic Avatar answered Sep 17 '26 03:09

Hackaholic


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']}
like image 35
AlvaroAV Avatar answered Sep 17 '26 05:09

AlvaroAV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!