Inverting a dictionary with list values

前端 未结 3 1259
爱一瞬间的悲伤
爱一瞬间的悲伤 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']}
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-27 23:05

    You can not use list objects as dictionary keys, since they should be hashable objects. You can loop over your items and use dict.setdefault method to create the expected result:

    >>> new = {}
    >>> 
    >>> for k,value in index.items():
    ...     for v in value:
    ...         new.setdefault(v,[]).append(k)
    ... 
    >>> new
    {'hue': ['Testfil2.txt', 'Testfil1.txt'], 'svend': ['Testfil1.txt'], 'abe': ['Testfil2.txt', 'Testfil1.txt'], 'tosse': ['Testfil1.txt'], 'pind': ['Testfil2.txt'], 'nisse': ['Testfil2.txt']}
    

    and if you are dealing with larger datasets for refusing of calling creating an empty list at each calling the setdefault() method you can use collections.defaultdict() which will calls the missing function just when it encounter a new key.

    from collections import defaultdict
    
    new = defaultdict(list)
    for k,value in index.items():
        for v in value:
            new[v].append(k)
    
    >>> new
    defaultdict(<type 'list'>, {'hue': ['Testfil2.txt', 'Testfil1.txt'], 'svend': ['Testfil1.txt'], 'abe': ['Testfil2.txt', 'Testfil1.txt'], 'tosse': ['Testfil1.txt'], 'pind': ['Testfil2.txt'], 'nisse': ['Testfil2.txt']})
    
    0 讨论(0)
提交回复
热议问题