![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
List of tuples to dictionary conversion in Python
In this article, we are going to learn how to convert the list of tuples into a dictionary. Converting a list of tuples into a dictionary is a straightforward thing.
Follow the below steps to complete the code.
- Initialize the list with tuples.
- Use the dict to convert given list of tuples into a dictionary.
- Print the resultant dictionary.
Example
Let's see the code.
# initializing the list tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)] # converting to dict result = dict(tuples) # printing the result print(result)
If you run the above code, you will get the following result.
Output
{'Key 1': 1, 'Key 2': 2, 'Key 3': 3, 'Key 4': 4, 'Key 5': 5}
Let's add value as list in the resultant dictionary using setdefault() method.
Follow the below steps to complete the code.
- Initialize the list with tuples.
- Iterate over the list of tuples.
- Set default value for the key and append the value.
- Print the result.
Example
Let's see the code.
# initializing the list tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)] # result result = {} # iterating over the tuples lists for (key, value) in tuples: # setting the default value as list([]) # appending the current value result.setdefault(key, []).append(value) # printing the list print(result)
If you run the above code, you will get the following result.
Output
{'Key 1': [1], 'Key 2': [2], 'Key 3': [3], 'Key 4': [4], 'Key 5': [5]}
Conclusion
If you have any queries in the article, mention them in the comment section.
Advertisements