Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return dictionary keys with the same list values

I have a dictionary like this:

example_dict = {'list_1': [1, 2, 'x'], 'list_2':[1, 3, 'x'], 'list_3' : [1, 2, 'x'], 'list_4': [1, 2, 'd'], 'list_5': [1, 3, 'x'] }

and need to return lists (or some other form) of keys that have the same values (lists) without knowing these values. The result should look something like this:

[['list_1', 'list_3'], ['list_2','list_5']]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can convert values to tuples and use them as a key in temporary dictionary:

Try:

example_dict = {
    "list_1": [1, 2, "x"],
    "list_2": [1, 3, "x"],
    "list_3": [1, 2, "x"],
    "list_4": [1, 2, "d"],
    "list_5": [1, 3, "x"],
}

out = {}
for k, v in example_dict.items():
    out.setdefault(tuple(v), []).append(k)

print(list(v for v in out.values() if len(v) > 1))

Prints:

[['list_1', 'list_3'], ['list_2', 'list_5']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading