Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

사전에 병합하는 Python 프로그램.

<시간/>

이 프로그램에서는 두 개의 사전이 제공됩니다. 우리의 임무는 이 두 목록을 병합하는 것입니다. 여기서는 update() 메서드를 사용합니다. 업데이트 방법은 두 목록을 병합하는 데 사용할 수 있습니다. 여기서 두 번째 목록은 첫 번째 목록에 병합됩니다. 새로운 목록이 생성되지 않았음을 의미하는 none을 반환합니다.

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

알고리즘

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.

예시 코드

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) 

출력

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}