这里给出一个元组,我们的任务是将元组转换为字典。为了解决这个问题,我们使用字典方法setdefault()。此方法有两个参数,将第一个参数转换为键,第二个参数转换为字典的值。Setdefault(键,值)是一个搜索键并显示其值的函数。
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}
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.
# 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))
输出结果
The Dictionary Is ::> {'Adwaita': 5, 'Aadrika': 5, 'Babai': 37, 'Mona': 7, 'Sanj': 25, 'Sakya': 30}