Inverting a dictionary with list values

前端 未结 3 1280
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 22:31

So, I have this index as a dict.

index = {\'Testfil2.txt\': [\'nisse\', \'hue\', \'abe\', \'pind\'], \'Testfil1.txt\': [\'hue\', \'abe\', 
\'tosse\', \'svend         


        
3条回答
  •  无人及你
    2020-11-27 22:44

    My solution for reversing a dictionary. However, it creates a new dictionary new_dic:

    new_dic = {}
    for k,v in index.items():
        for x in v:
            new_dic.setdefault(x,[]).append(k)
    

    Output :

    {'tosse': ['Testfil1.txt'], 'nisse': ['Testfil2.txt'], 'svend': ['Testfil1.txt'], 'abe': ['Testfil1.txt', 'Testfil2.txt'], 'pind': ['Testfil2.txt'], 'hue': ['Testfil1.txt', 'Testfil2.txt']}
    

提交回复
热议问题