TypeError:列表索引必须是整数或切片,而不是dict

时间:2018-09-03 18:59:01

标签: python dictionary

我正在尝试遍历具有相同索引的多个值的字典以解决重复值。

_av

我尝试了许多方法,请帮助我确定可能的错误。 输入文件如下:0:1,1:1,2:2,3:2,4:2,5:6, 输出应为1:[0,1],2:[2,3,4],6:[5,6,7],7:[8,9],12:[10],14:[11 ,12],15:[15,16],

谢谢

2 个答案:

答案 0 :(得分:0)

如果您有一组以上的嵌套字典,则

new_d = {'caseid1': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},
         'caseid2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},
         'caseid3': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},
         'caseid4': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},
         'caseid5': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},
         'caseid6': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6}}

a = defaultdict(list)

for k1, v1 in new_d.items():
    for k2, v2 in v1.items():
        a[f'{k1}_{v2}'].append(k2)

dict(a)

output:

{'caseid1_1': [0, 1],
 'caseid1_2': [2, 3, 4],
 'caseid1_6': [5],
 'caseid2_1': [0, 1],
 'caseid2_2': [2, 3, 4],
 'caseid2_6': [5],
 'caseid3_1': [0, 1],
 'caseid3_2': [2, 3, 4],
 'caseid3_6': [5],
 'caseid4_1': [0, 1],
 'caseid4_2': [2, 3, 4],
 'caseid4_6': [5],
 'caseid5_1': [0, 1],
 'caseid5_2': [2, 3, 4],
 'caseid5_6': [5],
 'caseid6_1': [0, 1],
 'caseid6_2': [2, 3, 4],
 'caseid6_6': [5]}

答案 1 :(得分:0)

好像您必须将a初始化为defaultdict,而不是列表

>>> from collections import defaultdict
>>> new2 = {'caseid': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6}}
>>> a = defaultdict(list)
>>> for x,y in new2['caseid'].items():
...     a[y].append(x)
... 
>>> print(a)
defaultdict(<class 'list'>, {1: [0, 1], 2: [2, 3, 4], 6: [5]})
>>> print(dict(a))
{1: [0, 1], 2: [2, 3, 4], 6: [5]}