Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Concatenate Tuple to Dictionary Key
When it is required to concatenate tuple elements to form dictionary keys, a list comprehension and the join() method are used. This technique converts tuples into string keys while preserving their associated values.
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}
Using Dictionary Comprehension
You can also achieve the same result using dictionary comprehension for a more concise approach ?
my_list = [(("pyt", "is", "best"), 10), (("pyt", "cool"), 1), (("pyt", "is", "fun"), 15)]
my_result = {" ".join(tuple_key): value for tuple_key, value in my_list}
print("The result is :")
print(my_result)
The result is :
{'pyt is best': 10, 'pyt cool': 1, 'pyt is fun': 15}
How It Works
A list of tuples is defined where each element contains a tuple (key elements) and a value.
An empty dictionary is created to store the results.
The list is iterated over, and
join()concatenates tuple elements into string keys.Each concatenated string becomes a dictionary key with its corresponding value.
Conclusion
Use join() to concatenate tuple elements into dictionary keys. Dictionary comprehension provides a more concise alternative to traditional loops for this operation.
