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

Chương trình Python để kết hợp với từ điển.

Trong Chương trình này, hai từ điển được đưa ra. Nhiệm vụ của chúng tôi là hợp nhất hai danh sách này. Ở đây chúng tôi sử dụng phương thức update (). Phương pháp cập nhật có thể sử dụng để hợp nhất hai danh sách. Ở đây danh sách thứ hai được hợp nhất vào danh sách đầu tiên. Nó không trả về điều gì có nghĩa là không có danh sách mới nào được tạo.

Ví dụ

Input::
A= ['AAA',10]
B= ['BBB',20]
Output::
C= {'BBB': 20, 'AAA': 10}

Thuật toán

Step 1: First create two User input dictionary.
Step 2: then use update() for merging. The second list is merged into the first list 
Step 3: Display the final dictionary.

Mã mẫu

def Merge(dict1, dict2): 
   return(dict2.update(dict1)) 
# Driver code 
d1 = dict()
d2=dict()
data = input('Enter Name & Roll separated by ":" ')
temp = data.split(':')
d1[temp[0]] = int(temp[1])
for key, value in d1.items():
   print('Name: {}, Roll: {}'.format(key, value))
data = input('Enter Name & Roll separated by ":" ')
temp = data.split(':')
d2[temp[0]] = int(temp[1])
for key, value in d2.items():
   print('Name: {}, Roll: {}'.format(key, value))
# This return None 
(Merge(d1, d2)) 
print("Dictionary after merging ::>",d2) 

Đầu ra

Enter Name & Roll separated by ":" AAA:10
Name: AAA, Roll: 10
Enter Name & Roll separated by ":" BBB:20
Name: BBB, Roll: 20
Dictionary after merging ::> {'BBB': 20, 'AAA': 10}