Python – Concatenate Tuple to Dictionary Key

PythonServer Side ProgrammingProgramming

When it is required to concatenate tuple to a dictionary key, a list comprehension and the ‘join’ attribute are used.

Example

Below is a demonstration of the same −

my_list = [(("pyt", "is", "best"), 10), (("pyt", "cool"), 1), (("pyt", "is", "fun"), 15)]

print("The list is :")
print(my_list)

my_result = {}
for sub_list in my_list:

   my_result[" ".join(sub_list[0])] = sub_list[1]

print("The result is :")
print(my_result)

Output

The list is :
[(('pyt', 'is', 'best'), 10), (('pyt', 'cool'), 1), (('pyt', 'is', 'fun'), 15)]
The result is :
{'pyt is best': 10, 'pyt cool': 1, 'pyt is fun': 15}

Explanation

  • A list of tuple is defined and is displayed on the console.

  • An empty dictionary is created.

  • The list is iterated over, and the list comprehension is used to remove spaces.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 08:23:41
Advertisements