Python - Concatenate Tuple to Dictionary Key
Last Updated :
28 Apr, 2023
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.
Python3
# Python3 code to demonstrate working of
# Concatenate Tuple to Dictionary Key
# Using loop + join()
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
# printing original list
print("The original list is : " + str(test_list))
res = {}
for sub in test_list:
# joining for making key
res[" ".join(sub[0])] = sub[1]
# printing result
print("The computed Dictionary : " + str(res))
OutputThe 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.
Python3
# Python3 code to demonstrate working of
# Concatenate Tuple to Dictionary Key
# Using dictionary comprehension
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
# printing original list
print("The original list is : " + str(test_list))
# one liner to solve problem
res = {' '.join(key): val for key, val in test_list}
# printing result
print("The computed Dictionary : " + str(res))
OutputThe 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:
- Initialize an empty dictionary res.
- Traverse the list using a for loop and take each tuple in the list.
- Convert the first element of the tuple (which is a tuple itself) into a string by joining its elements using a space separator. Ignore any empty elements.
- Add an entry in the dictionary with the key as the string generated in step 3 and the value as the second element of the tuple.
- Print the resulting dictionary.
Python3
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
# printing original list
print("The original list is : " + str(test_list))
res = {}
for sub in test_list:
# joining for making key
key = " ".join([elem for elem in sub[0] if len(elem) > 0])
res[key] = sub[1]
# printing result
print("The computed Dictionary : " + str(res))
OutputThe 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:
- Define a lambda function that takes a tuple and returns a tuple with the concatenated string as the first element and the second element as is.
- Use the map() function to apply the lambda function to each tuple in the list and create a new list of tuples.
- Use the dictionary() function to convert the list of tuples into a dictionary.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Concatenate Tuple to Dictionary Key
# Using dictionary() and map()
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
# printing original list
print("The original list is : " + str(test_list))
# using dictionary() and map()
res = dict(map(lambda x: (" ".join(x[0]), x[1]), test_list))
# printing result
print("The computed Dictionary : " + str(res))
OutputThe 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()
- Initialize the original list with tuples containing a tuple of strings and an integer.
- Use the zip() function to pair up the concatenated string keys and the integer values of the tuples in the original list.
- Use the dict() constructor to create a dictionary from the pairs generated by zip().
- Print the resulting dictionary.
Python3
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
# using dict() constructor and zip() to create dictionary
res = dict(zip([" ".join(sub[0]) for sub in test_list], [sub[1] for sub in test_list]))
# printing result
print("The computed Dictionary : " + str(res))
OutputThe 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
Python3
# Python3 code to demonstrate working of
# Concatenate Tuple to Dictionary Key
# Using reduce() and lambda function
from functools import reduce
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
# printing original list
print("The original list is : " + str(test_list))
# using reduce() and lambda function to create dictionary
res = reduce(lambda dict_obj, sub: dict_obj.update({" ".join(sub[0]):sub[1]}) or dict_obj, test_list, {})
# printing result
print("The computed Dictionary : " + str(res))
OutputThe 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)
Similar Reads
Python | Tuple key dictionary conversion Interconversions are always required while coding in Python, also because of expansion of Python as a prime language in the field of Data Science. This article discusses yet another problem that converts to dictionary and assigns keys as first pair elements as tuple and rest as itâs value. Letâs dis
5 min read
Python - Concatenate Dictionary string values The task of concatenating string values in a Python dictionary involves combining the values associated with the same key across multiple dictionaries. This operation allows us to merge string data in an efficient manner, especially when dealing with large datasets .For example, given two dictionari
4 min read
Create Dictionary Of Tuples - Python The task of creating a dictionary of tuples in Python involves mapping each key to a tuple of values, enabling structured data storage and quick lookups. For example, given a list of names like ["Bobby", "Ojaswi"] and their corresponding favorite foods as tuples [("chapathi", "roti"), ("Paraota", "I
3 min read
Convert Dictionary to List of Tuples - Python Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read
Python | Add dictionary to tuple Sometimes, while working with data, we can have a problem in which we need to append to a tuple a new record which is of form of Python dictionary. This kind of application can come in web development domain in case of composite attributes. Let's discuss certain ways in which this task can be perfor
4 min read