![]() |
VOOZH | about |
Given Tuples, convert them to the dictionary with key being concatenated string.
Input : test_list = [(("gfg", "is", "best"), 10), (("gfg", "for", "cs"), 15)]
Output : {'gfg is best': 10, 'gfg for cs': 15}
Explanation : Tuple strings concatenated as strings. Input : test_list = [(("gfg", "is", "best"), 10)]
Output : {'gfg is best': 10}
Explanation : Tuple strings concatenated as strings.Method #1 : Using loop + join()
In this, we perform the task of concatenation for the dictionary key using join() and loop is used to render the required dictionary.
The original list is : [(('gfg', 'is', 'best'), 10), (('gfg', 'good'), 1), (('gfg', 'for', 'cs'), 15)]
The computed Dictionary : {'gfg is best': 10, 'gfg good': 1, 'gfg for cs': 15}Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2: Using dictionary comprehension
This is shorthand to the above method, similar functionality, just a one-liner on paper for a compact solution.
The original list is : [(('gfg', 'is', 'best'), 10), (('gfg', 'good'), 1), (('gfg', 'for', 'cs'), 15)]
The computed Dictionary : {'gfg is best': 10, 'gfg good': 1, 'gfg for cs': 15}Method #3: Using For loop and join() method.
Algorithm:
The original list is : [(('gfg', 'is', 'best'), 10), (('gfg', 'good'), 1), (('gfg', 'for', 'cs'), 15)]
The computed Dictionary : {'gfg is best': 10, 'gfg good': 1, 'gfg for cs': 15}Time complexity: O(n*k) where n is the length of the input list and k is the length of the longest tuple in the list.
Space complexity: O(n) as we are storing the result in a dictionary
Method #4: Using dictionary() and map()
Approach:
Below is the implementation of the above approach:
The original list is : [(('gfg', 'is', 'best'), 10), (('gfg', 'good'), 1), (('gfg', 'for', 'cs'), 15)]
The computed Dictionary : {'gfg is best': 10, 'gfg good': 1, 'gfg for cs': 15}Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list, for creating the new list of tuples.
Method #5: Using dict() constructor and zip()
The computed Dictionary : {'gfg is best': 10, 'gfg good': 1, 'gfg for cs': 15}Time complexity: O(N), where n is the length of the original list.
Auxiliary space: O(N), where n is the length of the original list. This method creates two new lists, one for the concatenated string keys and one for the integer values, each with a length equal to the length of the original list.
Method #6: Using reduce() and lambda function from functools module
The original list is : [(('gfg', 'is', 'best'), 10), (('gfg', 'good'), 1), (('gfg', 'for', 'cs'), 15)]
The computed Dictionary : {'gfg is best': 10, 'gfg good': 1, 'gfg for cs': 15}Time Complexity: O(n)
Auxiliary Space: O(1)