Given a dictionary with string keys and sets as values the task is to write a python program to concatenate keys all of which have similar values order irrespective.
Input : test_dict = {'gfg' : {5, 4, 3}, 'is' : {4, 3, 5}, 'best' : {1, 4, 3}, 'for' : {1, 3, 4}, 'geeks' : {1, 2, 3}}
Output : {'gfg-is': frozenset({3, 4, 5}), 'best-for': frozenset({1, 3, 4}), 'geeks': frozenset({1, 2, 3})}
Explanation : Similar set keys are concatenated, {5, 4, 3} == {4, 3, 5}, hence gfg-is are concatenated.
Input : test_dict = {'gfg' : {5, 4, 3}, 'is' : {4, 3, 5}, 'geeks' : {1, 2, 3}}
Output : {'gfg-is': frozenset({3, 4, 5}), 'geeks': frozenset({1, 2, 3})}
Explanation : Similar set keys are concatenated, {5, 4, 3} == {4, 3, 5}, hence gfg-is are concatenated.
In this, we perform the task of hashing each set and appending corresponding keys using defaultdict(). The next step is to join all the hashed keys to similar set values.
The original dictionary is : {'gfg': {3, 4, 5}, 'is': {3, 4, 5}, 'best': {1, 3, 4}, 'for': {1, 3, 4}, 'geeks': {1, 2, 3}}
The concatenated keys : {'gfg-is': frozenset({3, 4, 5}), 'best-for': frozenset({1, 3, 4}), 'geeks': frozenset({1, 2, 3})}
In this, we perform tasks of grouping like elements using groupby(). After that joining alike valued keys is done using join().
The original dictionary is : {'gfg': {3, 4, 5}, 'is': {3, 4, 5}, 'best': {1, 3, 4}, 'for': {1, 3, 4}, 'geeks': {1, 2, 3}}
The concatenated keys : {'gfg-is': {3, 4, 5}, 'best-for': {1, 3, 4}, 'geeks': {1, 2, 3}}
OutputThe original dictionary is : {'gfg': {3, 4, 5}, 'is': {3, 4, 5}, 'best': {1, 3, 4}, 'for': {1, 3, 4}, 'geeks': {1, 2, 3}}
The concatenated keys : {'gfg-is': {3, 4, 5}, 'best-for': {1, 3, 4}, 'geeks': {1, 2, 3}}
Time complexity: O(n^2), where n is the number of key-value pairs in the dictionary. This is because we need to compare each pair of keys with each other.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary. This is because we need to create a set to store the processed keys, which can have up to n elements.
OutputThe original dictionary is : {'gfg': {3, 4, 5}, 'is': {3, 4, 5}, 'best': {1, 3, 4}, 'for': {1, 3, 4}, 'geeks': {1, 2, 3}}
The concatenated keys : {'best-for': {1, 3, 4}, 'geeks': {1, 2, 3}, 'gfg-is': {3, 4, 5}}