类型错误:列表索引必须是整数或切片,而不是 dict

我正在尝试迭代具有相同索引的多个值的字典以解释重复值。


a = []

for x,y in new2.items():

    a[y].append(x)

print(a)

我尝试了很多方法,请帮助我确定可能的错误。输入文件是这样的: 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],


慕码人2483693
浏览 185回答 2
2回答

杨魅力

看起来您必须初始化a为 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():...&nbsp; &nbsp; &nbsp;a[y].append(x)...&nbsp;>>> 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]}

神不在的星期二

如果您有一组以上的嵌套字典new_d = {'caseid1': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'caseid2': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'caseid3': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'caseid4': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'caseid5': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'caseid6': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6}}a = defaultdict(list)for k1, v1 in new_d.items():&nbsp; &nbsp; for k2, v2 in v1.items():&nbsp; &nbsp; &nbsp; &nbsp; a[f'{k1}_{v2}'].append(k2)dict(a)output:{'caseid1_1': [0, 1],&nbsp;'caseid1_2': [2, 3, 4],&nbsp;'caseid1_6': [5],&nbsp;'caseid2_1': [0, 1],&nbsp;'caseid2_2': [2, 3, 4],&nbsp;'caseid2_6': [5],&nbsp;'caseid3_1': [0, 1],&nbsp;'caseid3_2': [2, 3, 4],&nbsp;'caseid3_6': [5],&nbsp;'caseid4_1': [0, 1],&nbsp;'caseid4_2': [2, 3, 4],&nbsp;'caseid4_6': [5],&nbsp;'caseid5_1': [0, 1],&nbsp;'caseid5_2': [2, 3, 4],&nbsp;'caseid5_6': [5],&nbsp;'caseid6_1': [0, 1],&nbsp;'caseid6_2': [2, 3, 4],&nbsp;'caseid6_6': [5]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python