我有一个列表l1
,如下所示:
l1 = [[(1,"INC1"), (1, "INC2")],[(3, "INC4"),(4, "INC6")]]
我有一个列表names
,如下所示:
names = ['John', 'Marcia']
我有另一个列表label_issue_list
,如下所示:
label_issue_list = [["Problem1","Problem1"],["Problem3","Problem4"]]
所有三个列表的索引都连接起来,如下面的输出所示。
我试图使用所有这三个列表并获得一个字典输出,如下所示:
{
"John" : {
"Problem1" : 2,
"tick_info" : {"1": ["INC1", "INC2"]}
},
"Marcia" : {
"Problem3" : 1,
"Problem4" : 1,
"tick_info" : {"3":["INC4"], "4":["INC6"]}
}
}
我尝试了以下代码,但这似乎不起作用:
clust_stack = {}
for i in range(len(l1)):
fq= defaultdict( list )
for n,v in l1[i]:
fq[str(n)].append(v)
for name_, data in zip(names, label_issue_list)[i]:
clust_stack[name_] = Counter(map(str,data))
clust_stack[name_]["tick_info"] = {}
clust_stack[name_]["tick_info"] = dict(fq)
我在for name_, data in zip(names, label_issue_list)[i]:
行中收到以下错误:
ValueError: too many values to unpack
我需要做什么才能获得所需的输出?
答案 0 :(得分:1)
从压缩所有3个列表开始:
clust_stack = {}
for name, data, fq in zip(names, label_issue_list, l1):
clust_stack[name] = dict(Counter(data)) # turn back into regular dictionary
tick_info = clust_stack[name]['tick_info'] = {}
for num, tick in fq:
tick_info.setdefault(num, []).append(tick)
使用Counter
计算每个l1
元素中的信息非常好,但您需要将该结果转回常规字典,以便为其添加其他键。
然后,您可以将tick_info
密钥添加到该密钥,以每个密钥的列表值收集这些列表中的信息。
演示:
>>> from collections import Counter
>>> from pprint import pprint
>>> l1 = [[(1,"INC1"), (1, "INC2")],[(3, "INC4"),(4, "INC6")]]
>>> names = ['John', 'Marcia']
>>> label_issue_list = [["Problem1","Problem1"],["Problem3","Problem4"]]
>>> clust_stack = {}
>>> for name, data, fq in zip(names, label_issue_list, l1):
... clust_stack[name] = dict(Counter(data)) # turn back into regular dictionary
... tick_info = clust_stack[name]['tick_info'] = {}
... for num, tick in fq:
... tick_info.setdefault(num, []).append(tick)
...
>>> pprint(clust_stack)
{'John': {'Problem1': 2, 'tick_info': {1: ['INC1', 'INC2']}},
'Marcia': {'Problem3': 1,
'Problem4': 1,
'tick_info': {3: ['INC4'], 4: ['INC6']}}}