Python – Concatenate Tuple to Dictionary Key

Given Tuples, convert them to 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 dictionary key using join() and loop is used to render the required dictionary.



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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 #2 : Using dictionary comprehension

This is shorthand to above method, similar functionality, just one-liner on paper for compact solution.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.