
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Concatenate Tuple to Dictionary Key in Python
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.
Advertisements