Transform dictionary to map values to list of keys

Viewed 42

For example I have a dictionary like this:

my_dict = {
    'name_1': 'method_name_x',
    'name_2': 'method_name_x',
    'name_3': 'method_name_y',
}

(keys and values of the dictionary are simply strings)

I want to transform this dictionary so that all values will be mapped to a list of keys which have these value.

Example result:

my_transformed_dict = {
    'method_name_x': ['name_1', 'name_2'],
    'method_name_y': ['name_3'],
}

I could do this by the following code:

my_transformed_dict = dict.fromkeys(my_dict.values(), [])
for k, v in my_dict.items():
    my_transformed_dict[v].append(k)

But this will end up addind every key to the values somehow.


I also thought of using dict.setdefault(), like this:

my_transformed_dict = dict()
for k, v in my_dict:
    my_transformed_dict.setdefault(v, []).append(k)

This works as indentend, but:

What would be best practice to solve this?

Is there a simpler way to solve this (maybe using a library)? Or just doing the code as a readable one-liner?

1 Answers

You can use itertools.groupby, for example:

from itertools import groupby

my_dict = {
    'name_1': 'method_name_x',
    'name_2': 'method_name_x',
    'name_3': 'method_name_y',
}
print({k: list(v) for k, v in groupby(sorted(my_dict, key=lambda k: my_dict[k]), key=lambda k: my_dict[k])})

Output:

{'method_name_x': ['name_1', 'name_2'], 'method_name_y': ['name_3']}
Related