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

Found keys with the same values, combine them in tuple and return updated dictionary

I’m trying to sort the following dictionary:

test_dict = {
        'a': [1,3,5],
        'b': [9,3,4],
        'c': [4,5,6],
        'd': [1,3,6],
        'e': [1,3,5],
        'f': [1,3,5],
        'g': [4,5,6],
        'h': [6,5,9]
        }

I have to combine all keys with duplicated values in the tuple as the dictionary key with one value they have.

As result, i’d like to get something like that:

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

result = {
        ('a','e','f'): [1,3,5],
        'b': [9,3,4],
        ('c','g'): [4,5,6],
        'd': [1,3,6],
        'h': [6,5,9]
        }

I’ve tried a lof of things, but i implemented only search by value:

test_dict = {
        'a': [1,3,5],
        'b': [9,3,4],
        'c': [4,5,6],
        'd': [1,3,6],
        'e': [1,3,5],
        'f': [1,3,5],
        'g': [4,5,7],
        'h': [6,5,9]
        }


list_to_find = [1,3,5]


def found_duplicates(target_dict, value_to_find):

    found_keys = []

    for k in test_dict.keys():
        value_for_k = test_dict[k]
        if(value_for_k == list_to_find):
            found_keys.append(k)
    return tuple(found_keys)

print(found_duplicates(test_dict, list_to_find))

Whats the better way to find all duplicate values, combine keys for that value in one tuple and return new dict?

>Solution :

Try:

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


out = {v[0] if len(v) == 1 else tuple(v): list(k) for k, v in out.items()}
print(out)

Prints:

{
    ("a", "e", "f"): [1, 3, 5],
    "b": [9, 3, 4],
    ("c", "g"): [4, 5, 6],
    "d": [1, 3, 6],
    "h": [6, 5, 9],
}
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