
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Concatenate Keys with Similar Values in Python
Python's implementation of a data structure known more commonly as an associative array is a dictionary. A dictionary is made up of a group of key-value pairs. Each key-value combination corresponds to a key and its corresponding value.
In this article, we will learn how to concatenate all keys which have similar values in python.
Methods Used
The following are the various methods to accomplish this task:
Using defaultdict() and join() functions
Using dictionary comprehension, groupby() and join() functions
Example
Assume we have taken an input dictionary. We will now concatenate all the keys which are having similar values(excluding the order) using the above methods.
Input
inputDict = {'hello': {2, 8, 6}, 'tutorialspoint' ? {6,7,5}, 'all': {8, 2, 6}, 'users': {5, 6, 7}, 'python'? {10, 1, 9}}
Output
{'hello-all': frozenset({8, 2, 6}), 'tutorialspoint-users' ? frozenset({5, 6, 7}), 'python'? frozenset({1, 10, 9})}
Here in this input dictionary, the keys 'hello', 'all' are having the same values {2, 8, 6} and {8, 2, 6} excluding the order. So, they are concatenated together with a hyphen(-).
Similarly, the keys 'tutorialspoint' and 'users' also have the same values. Hence they are also grouped together.
Method 1 Using defaultdict() and join() functions
defaultdict() ? It is a dictionary's sub-class that returns a dictionary-like object. The only significant difference between dictionaries and defaultdict in terms of functionality is that the defaultdict never raises a KeyError. If a key doesn't exist, it offers a default value.
Syntax
defaultdict(default_factory)
default_factory ? It is a function that returns the dictionary's default value. If this argument is missing, the dictionary throws a KeyError.
join() ? join() is a string function in Python that is used to join elements of a sequence that are separated by a string separator. This function connects sequence elements to convert to a string
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task -.
Use the import keyword to import defaultdict from the collections module.
Create a variable to store the input dictionary.
Print the input dictionary.
Create a default dictionary to store hash values.
Use the for loop to traverse through the key and value pairs of the input dictionary using the items() function(returns a view object i.e, it contains the key-value pairs of the dictionary, as tuples in a list).
Convert the values of the dictionary to frozenset using the frozenset() function(a built-in function that returns an immutable frozenset object initialized with elements from the specified iterable)
Add this value along with the key to the hash Values.
Traverse through the hashValues dictionary and join the similar keys with ?-' as delimiter using the join() function.
Print the resultant dictionary after concatenating all keys having similar values.
Example
The following program returns a dictionary after concatenating all keys having similar values in an input dictionary using defaultdict() and join() functions -
# importing defaultdict from the collections module from collections import defaultdict # input dictionary inputDict = {'hello': {2, 8, 6}, 'tutorialspoint': {6, 7, 5}, 'all': { 8, 2, 6}, 'users': {5, 6, 7}, 'python': {10, 1, 9}} # printing input dictionary print("Input dictionary:\n", inputDict) # Creating a default dictionary to store hash values hashValues = defaultdict(list) # travsering through the key, value pairs of input dictionary for key, value in inputDict.items(): # Convert values of the dictionary to frozenset and append this key to hashValues hashValues[frozenset(value)].append(key) # joining the key having similar values with hyphen(-) ouputDict = {'-'.join(keys): values for (values, keys) in hashValues.items()} # printing resultant dictionary print("Resultant dictionary after concatenating all keys having similar values:\n", ouputDict)
Output
On executing, the above program will generate the following output -
Input dictionary: {'hello': {8, 2, 6}, 'tutorialspoint': {5, 6, 7}, 'all': {8, 2, 6}, 'users': {5, 6, 7}, 'python': {1, 10, 9}} Resultant dictionary after concatenating all keys having similar values: {'hello-all': frozenset({8, 2, 6}), 'tutorialspoint-users': frozenset({5, 6, 7}), 'python': frozenset({1, 10, 9})}
Method 2 Using dictionary comprehension, groupby() and join() functions
itertools.groupby() function
Groups objects of a similar type into an iterator object.
The keys for each element in the iterable are determined using this function.
Syntax
itertools.groupby(iterable, key_func)
Parameters
iterable ? It is iterable like a list, dictionary tuple, etc.
key_func ? It is a function that computes keys for each element in an iterable.
return value ? returns key and iterable of grouped items. If no key is given, the identity function is used by default.
sorted() function
It returns a sorted list of the iterable object given.
You can choose between ascending and descending order. Numbers are sorted numerically, while strings are arranged alphabetically.
Syntax
sorted(iterable, key=key, reverse=reverse)
Parameters
iterable ? It is a sequence.
key ? A function that will be executed to determine the order. The default value is None
reverse ? A Boolean expression. True sorts ascending, False sorts descending. The default value is False
Example
The following program returns a dictionary after concatenating all keys having similar values in an input dictionary using dictionary comprehension, groupby() and join() functions -
# importing groupby from itertools module from itertools import groupby # input dictionary inputDict = {'hello': {2, 8, 6}, 'tutorialspoint': {8, 6, 2}, 'all': { 2, 4, 3}, 'users': {2, 3, 4}, 'python': {10, 1, 9}} print("Input dictionary:\n", inputDict) # Traverse in the sorted Dictionary with the key as the value of the dictionary # Join the similar keys with - as a delimiter using the join() function # Here similar elements are grouped using the groupby() function ouputDict = {'-'.join(v): k for k, v in groupby( sorted(inputDict, key=inputDict.get), key=lambda i: inputDict[i])} # printing resultant dictionary print("Resultant dictionary after concatenating all keys having similar values:\n", ouputDict)
Output
On executing, the above program will generate the following output -
Input dictionary: {'hello': {8, 2, 6}, 'tutorialspoint': {8, 2, 6}, 'all': {2, 3, 4}, 'users': {2, 3, 4}, 'python': {1, 10, 9}} Resultant dictionary after concatenating all keys having similar values: {'hello-tutorialspoint': {8, 2, 6}, 'all-users': {2, 3, 4}, 'python': {1, 10, 9}}
Conclusion
In this article, we studied two distinct ways to concatenate all keys with similar values. We also learned how to group similar key, and value pairs from the dictionary using the groupby method.