This is a Basic program to convert a list of Tuples into Dictionary. It works in 3 steps:Program:1. Creating a class2. Creating a function inside the class3. Calling the function from main with object and argument.The function "tupleToDict" is used to convert a list of Tuples into Dictionary by using the Type conversion or type casting.In this, first the list of tuple is formed by entering tuples one by one and then it is typecasted to dictionary.
Output:#Python program to Convert a list of Tuples into Dictionary class convert(): def __init__(self, arg): self.arg = arg def tupleToDict(self): return dict(self.arg) if __name__=='__main__': lst=[] n=int(input('Enter the number of tuples in the list = ')) print('Enter elements of the list:-') # combinig tuples and forming list. for i in range(n): print('tuple ',(i+1),' :-') temp = [] temp.append(input('Key = ')) temp.append(int(input('Value = '))) nt = tuple(temp) lst.append(nt) print('The entered list is = ',lst) obj = convert(lst) new = obj.tupleToDict() print('The resulting dictionary is = ',new)
Enter the number of tuples in the list = 4 Enter elements of the list:- tuple 1 :- Key = hi Value = 1 tuple 2 :- Key = hello Value = 2 tuple 3 :- Key = yeh Value = 4 tuple 4 :- Key = no Value = 6 The entered list is = [('hi', 1), ('hello', 2), ('yeh', 4), ('no', 6)] The resulting dictionary is = {'hi': 1, 'hello': 2, 'yeh': 4, 'no': 6}
Comments