
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to convert a list of tuples into Dictionary
Here one tuple is given, our task is to convert tuples to dictionary. To solve this problem we use the dictionary method setdefault (). This method has two parameter, to convert the first parameter to key and the second to the value of the dictionary. Setdefault (key, value) is a function searches for a key and displays its value.
Example
Input: [("Adwaita", 5), ("Aadrika", 5), ("Babai", 37), ("Mona", 7), ("Sanj", 25), ("Sakya", 30)] Output: {'Adwaita': 5, 'Aadrika': 5, 'Babai': 37, 'Mona': 7, 'Sanj': 25, 'Sakya': 30}
Algorithm
Step 1: Tuple is given. Step 2: To convert the first parameter to key and the second to the value of the dictionary. Step 3: Setdefault (key, value) function searches for a key and displays its value and creates a new key with value if the key is not present. Step 4: Using the append function we just added the values to the dictionary.
Example Code
# Python code to convert into dictionary def listtodict(A, di): di = dict(A) return di # Driver Code A = [("Adwaita", 5), ("Aadrika", 5), ("Babai", 37), ("Mona", 7), ("Sanj", 25), ("Sakya", 30)] di = {} print ("The Dictionary Is ::>",listtodict(A, di))
Output
The Dictionary Is ::> {'Adwaita': 5, 'Aadrika': 5, 'Babai': 37, 'Mona': 7, 'Sanj': 25, 'Sakya': 30}
- Related Articles
- Convert dictionary to list of tuples in Python
- Convert list of tuples into list in Python
- Convert list of tuples into digits in Python
- List of tuples to dictionary conversion in Python
- Python - Convert list of nested dictionary into Pandas Dataframe
- Python program to convert elements in a list of Tuples to Float
- Python program to Convert a elements in a list of Tuples to Float
- Convert list of tuples to list of list in Python
- Python program to Convert Matrix to Dictionary Value List
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- How to convert dictionary into list of JavaScript objects?
- Python - Convert a set into dictionary
- Python Convert nested dictionary into flattened dictionary?
- Python - Convert flattened dictionary into nested dictionary

Advertisements