Python程序将元组列表转换为Dictionary
这里给出一个元组,我们的任务是将元组转换为字典。为了解决这个问题,我们使用字典方法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}热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志