Python program to merge to dictionaries.

PythonProgrammingServer Side Programming

In this Program two dictionaries are given. Our task is to merge this two list. Here we use update () method. Update method can use for merging two list. Here the second list is merged into the first list. It returns none that means no new list is created.

Example

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

Algorithm

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.

Example Code

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) 

Output

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}
raja
Published on 25-Sep-2018 12:53:10
Advertisements