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}

Advertisements