Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Concatenate Tuple to Dictionary Key

Python – Concatenate Tuple to Dictionary Key

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))


Output

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.

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))


Output

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:

  1. Initialize an empty dictionary res.
  2. Traverse the list using a for loop and take each tuple in the list.
  3. 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.
  4. 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.
  5. 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))


Output

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:

  1. 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.
  2. Use the map() function to apply the lambda function to each tuple in the list and create a new list of tuples.
  3. 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))


Output

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()

  1. Initialize the original list with tuples containing a tuple of strings and an integer.
  2. Use the zip() function to pair up the concatenated string keys and the integer values of the tuples in the original list.
  3. Use the dict() constructor to create a dictionary from the pairs generated by zip().
  4. 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))


Output

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

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))


Output

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)

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments