Python 使用列表列表创建json
如果有我的数据是这种格式Python 使用列表列表创建json,python,json,list,dictionary,Python,Json,List,Dictionary,如果有我的数据是这种格式 a=[(0,0,'customer',["Hi, I'm user"]), (0,1,'agent',['Hi Welcome']), (0, 2,'customer',["i would like to know"]), (0, 3, 'agent', ['Yes','Only credit']), (0, 4, 'customer', ['oic...','sub line?','is it?']), (0, 5, 'agent', ['no sublin
a=[(0,0,'customer',["Hi, I'm user"]),
(0,1,'agent',['Hi Welcome']),
(0, 2,'customer',["i would like to know"]),
(0, 3, 'agent', ['Yes','Only credit']),
(0, 4, 'customer', ['oic...','sub line?','is it?']),
(0, 5, 'agent', ['no subline']),
(0, 6, 'customer', ['oic...','by','bye']),
(1,0,'customer',["Hi, I'm user"]),
(1,1,'agent',['Hi Welcome']),
(1, 2,'customer',["i would like to know"]),
(1, 3, 'agent', ['Yes','Only credit'])]
需要转换成json格式,格式如下
{
0:
{
0:{
'utterance': ["Hi, I'm use],
'speaker': 'customer'
},
1:{
'utterance': ['Hi Welcome'],
'speaker': 'agent'
...
},
6:{'utterance':['oic...','by','bye'],
'speaker': 'customer'
}
}
...
1:{
3: {
'utterance':['Yes','Only credit'],
'speaker':'agent'
}
}
}
我无法得到上面所给的词典。如果有任何帮助,我们将不胜感激 我通常使用Pandas将列表转换为json,但这种结构相当复杂。因此,手动解决方案是:
a = [(0, 0, 'customer', ["Hi, I'm user"]),
(0, 1, 'agent', ['Hi Welcome']),
(0, 2, 'customer', ["i would like to know"]),
(0, 3, 'agent', ['Yes', 'Only credit']),
(0, 4, 'customer', ['oic...', 'sub line?', 'is it?']),
(0, 5, 'agent', ['no subline']),
(0, 6, 'customer', ['oic...', 'by', 'bye']),
(1, 0, 'customer', ["Hi, I'm user"]),
(1, 1, 'agent', ['Hi Welcome']),
(1, 2, 'customer', ["i would like to know"]),
(1, 3, 'agent', ['Yes', 'Only credit'])]
files = {}
for item in a:
if not item[0] in files:
files[item[0]] = {item[1]: {'utterance': item[2], 'speaker': item[3]}}
else:
val = files[item[0]]
val[item[1]] = {'utterance': item[2], 'speaker': item[3]}
files[item[0]] = val
print(files)