Search code examples
pythondictionarypython-itertools

Reverse a dictionary using single "for" loop or using "itertools" library


I have a dictionary of lists like this:

my_dict = {
    'key_a': [1, 3, 4],
    'key_b': [0, 2],
}

I want to create a reverse lookup dict like this:

reverse_dict = {
    0: 'key_b',
    1: 'key_a',
    2: 'key_b',
    3: 'key_a',
    4: 'key_a',
}

I have a working version of the solution:

reverse_dict = {elem: key for key, a_list in my_dict.items() for elem in a_list}

But wanted to know if someone can provide an alternate answer that doesn't use a double for as I feel it loses readability. So I'd prefer having a single for loop or use functions like the ones in itertools or functional programming


Solution

  • Your solution using dictionary comprehension is the Pythonic way to achieve it.

    However, as an alternative with single for loop as requested by you, here is the functional one using zip(), itertools.repeat(), and itertools.chain.from_iterable(), but I doubt that it is any better then yours solution in terms of readability:

    my_dict = {
        'key_a': [1, 3, 4],
        'key_b': [0, 2],
    }
    
    from itertools import chain, repeat
    
    new_dict = dict(chain.from_iterable(zip(v, repeat(k)) for k, v in my_dict.items()))
    

    where new_dict will hold:

    {0: 'key_b', 1: 'key_a', 2: 'key_b', 3: 'key_a', 4: 'key_a'}