在其他for循环中将新值附加到现有(反向)字典中

时间:2018-09-16 17:20:43

标签: python list dictionary merge

我创建了一个带for循环的字典。

现在我想将列表中单词的索引值添加到此字典中。

因此必须将enumerate(olist)中num的值添加到字典中的相应单词。

代码:

def reverse_dict(input):
    output = collections.defaultdict(list)

    for key, val in input.items():
        for item in val:
            output[item].append(key)

    return output


def main():
    olist = []
    worddict = {} 

    for line in sys.stdin:
        i,u,t,w = line.split('\t')
        splitword = (w.split())
        olist.extend(splitword)
        worddict[i] = splitword




    for num,name in enumerate(olist):
        #splitword.extend([num])
        #worddict[i].extend([num])
        print("{} [{}]".format(name.strip(), num))

    output = reverse_dict(worddict)
    print(output)

当前输出1:

RT [0]
@AfshinEllian1 [1]
: [2]
Kennelijk [3]
vinden [4]
ze [5]
daar [6]
etc..

电流输出2:

{'RT': ['1035421930541772800', '1035421931321864192'], '@AfshinEllian1': ['1035421930541772800'], ':': ['1035421930541772800', '1035421931321864192'], 'Kennelijk': ['1035421930541772800'], 'vinden': ['1035421930541772800'], 'ze': ['1035421930541772800'], 'daar': ['1035421930541772800'], 'aan': ['1035421930541772800'], 'die': ['1035421930541772800'], 'gezellige': ['1035421930541772800'], 'tafel': ['1035421930541772800'], 'normaal': ['1035421930541772800'], 'dat': ['1035421930541772800'], 'steltje': ['1035421930541772800'], 'barbaren': ['1035421930541772800'], 'onze': ['1035421930541772800'], 'grondwettelijke': ['1035421930541772800'], 'rechten': ['1035421930541772800'], 'bedreigen': ['1035421930541772800'], '.': ['1035421930541772800'], 'Zouden': ['1035421930541772800'], 'we': ['1035421930541772800'], 'ook': ['1035421930541772800']

预期输出:

{'RT': ['1035421930541772800', '1035421931321864192', '0'], 
'@AfshinEllian1': ['1035421930541772800', '1']

1 个答案:

答案 0 :(得分:0)

如果我正确理解,给定列表和反向字典,您希望将每个项目的索引附加到字典中的相应条目。也许会做到这一点:

d = reverse_dict(worddict)

for num, name in enumerate(olist):
    d[name].append(num)

现在,字典d将是您期望的字典。