Question 36: Write a Python script to concatenate following dictionaries to create a new one.
a. Sample Dictionary: b. dic1 = {1:10, 2:20}
c. dic2 = {3:30, 4:40} d. dic3 = {5:50,6:60}
Download hole Program / Project code, by clicking following link:
What is the output of the following program?
# Define the first dictionary
dictionary1 = {'Google': 1, 'Facebook': 2, 'Microsoft': 3}
# Define the second dictionary
dictionary2 = {'GFG': 1, 'Microsoft': 2, 'Youtube': 3}
# Merge the contents of dictionary2 into dictionary1
dictionary1.update(dictionary2)
# Print the merged dictionary
for key, value in dictionary1.items():
print(key, value)
dictionary1 = {'Google': 1, 'Facebook': 2, 'Microsoft': 3}
# Define the second dictionary
dictionary2 = {'GFG': 1, 'Microsoft': 2, 'Youtube': 3}
# Merge the contents of dictionary2 into dictionary1
dictionary1.update(dictionary2)
# Print the merged dictionary
for key, value in dictionary1.items():
print(key, value)
The provided Python program combines the contents of two dictionaries, dictionary1 and dictionary2, using the update() method, and then prints the key-value pairs in the resulting merged dictionary. When dictionaries are updated using update(), values from dictionary2 overwrite those in dictionary1 if they have the same keys.
Here's the expected output of the program:
Google 1
Facebook 2
Microsoft 2
Youtube 3
Google 1
Facebook 2
Microsoft 2
Youtube 3
Explanation:
- Initially, dictionary1 contains three key-value pairs, and dictionary2 contains three different key-value pairs.
- After the dictionary1.update(dictionary2) line, dictionary1 is updated with the contents of dictionary2. The key 'Microsoft' exists in both dictionaries, so the value from dictionary2 (which is 2) overwrites the value in dictionary1.
- The for loop then prints each key-value pair in the merged dictionary1.
Programming Code:
Following code write in: BP_P36.py
# Concatenate following Dictionary & create new one # dic1 = {1:10, 2:20} # dic2 = {3:30, 4:40} # dic3 = {5:50, 6:60} dic1 = {1:10, 2:20} dic2 = {3:30, 4:40} dic3 = {5:50, 6:60} print("Dictionary 1 is: ", dic1) print("Dictionary 2 is: ", dic2) print("Dictionary 3 is: ", dic3) # empty dictionary dic4 = {} print("Empty Dictionary 4 is: ", dic4) # concatenate for d in (dic1, dic2, dic3): dic4.update(d) # update() function print("After Concatenation Dictionary 4 is: ", dic4) # Thanks for Reading.
Output:
0 Comments