Search code examples
pythonperformancepython-3.xdefaultdict

how to efficiently do a reverse look up in defaultdict?


I did some search before posting this question, it seems there are few different ways to accomplish this.

But what is the most efficient way currently (using Python 3) to search for a key based on a specific value in a defaultdict which looks (something) like this:

defaultdict(list,
            {'a': [[2, 3], [1, 2]],
             'b': [[5, 6]],
             'w': [[]],
             'x': [[9]],
             'z': [[5, 6]]})

I want to find all keys that have a value of say 6. One solution is to write a nested for loop that iterates over the key, value of the defaultdict, but I am sure there is a better way to accomplish this.


Solution

  • You can use chain.from_iterable from itertools module like this example:

    from itertools import chain 
    
    a = defaultdict(list,
                {'a': [[2, 3], [1, 2]],
                 'b': [[5, 6]],
                 'w': [[]],
                 'x': [[9]],
                 'z': [[5, 6]]})
    
    keys =  [k for k, v in a.items() if 6 in chain.from_iterable(v)]
    print(keys)
    

    Or, in a more compact way, you can define a function that do a lookup in your defaultdict's values:

    def get_keys(a, key=6):
        return [k for k, v in a.items() if key in chain.from_iterable(v)]
    
    keys = get_keys(a)
    print(keys)
    

    Output:

    ['b', 'z']