Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để chuyển đổi một danh sách các bộ giá trị thành Từ điển

Ở đây đưa ra một tuple, nhiệm vụ của chúng ta là chuyển đổi các tuple sang từ điển. Để giải quyết vấn đề này, chúng tôi sử dụng phương thức từ điển setdefault (). Phương thức này có hai tham số, để chuyển đổi tham số đầu tiên thành khóa và tham số thứ hai thành giá trị của từ điển. Setdefault (khóa, giá trị) là một hàm tìm kiếm khóa và hiển thị giá trị của nó.

Ví dụ

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}

Thuật toán

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.

Mã mẫu

# 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)) 

Đầu ra

The Dictionary Is ::> {'Adwaita': 5, 'Aadrika': 5, 'Babai': 37, 'Mona': 7, 'Sanj': 25, 'Sakya': 30}