Home > Software design >  Found keys with the same values, combine them in tuple and return updated dictionary
Found keys with the same values, combine them in tuple and return updated dictionary

Time:11-03

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:

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?

CodePudding user response:

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],
}
  • Related