Inverting a dictionary with list values

前端 未结 3 1279
爱一瞬间的悲伤
爱一瞬间的悲伤 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:58

    I've tried around and you want to use val not in inverse but it can't be checked if a "list is in a dict". (val is a list)

    For your code a simple change will do what you want:

    def invert_dict(d): 
        inverse = dict() 
        for key in d: 
            # Go through the list that is saved in the dict:
            for item in d[key]:
                # Check if in the inverted dict the key exists
                if item not in inverse: 
                    # If not create a new list
                    inverse[item] = [key] 
                else: 
                    inverse[item].append(key) 
        return inverse
    

提交回复
热议问题