To keep the duplicates and conform the input format:
import collections
import json
string = "[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]"
d = collections.defaultdict(list)
for (k, v1, v2) in json.loads(string.replace("'",'"')):
d[k].append((v1, v2))
With eval
(if you trust your input):
import collections
string = "[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]"
d = collections.defaultdict(list)
for (k, v1, v2) in eval(string):
d[k].append((v1, v2))
Contents of d:
defaultdict(<type 'list'>, {
'q1': [('0', 'q1'), ('1', 'q2')],
'q2': [('0', 'q2'), ('1', 'q1')]
})
EDIT: and with no library at all.
string = "[['q1', '0', 'q1'], ['q1', '1', 'q2'], ['q2', '0', 'q2'], ['q2', '1', 'q1']]"
d = {}
for (k, v1, v2) in eval(string):
d.setdefault(k, []).append((v1, v2))
I'm unable to make it a one-liner though :-)