Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

merging
communitycreator

How to merge two dictionaries in python

vamsikrishna

Dictionary

A dictionary is a collection of key-value pairs or items that can be referred to using a key name.

In a dictionary…

  1. Duplicate items are unordereditems do not have a specific order, changeable, and do not allow duplicates.

  2. Values can be of any data type and duplicated, whereas keys can’t be repeated and must be immutable.

  3. Dictionary keys are case sensitive.

Two methods

  1. update() method
  2. ** method

Explanation

  1. First, we create a dictionary (d1) with the values set as fruit names.
  2. Then, we print that dictionary.
  3. Next, we initialize a variable (d3) and give it the same value as the dictionary (d1).
  4. Then, we create dictionary d1 with key values 4,5,6 and other fruits as values.
  5. Next, we initialize a variable (d4) and give it the dictionary (d2).
  6. Next, the update method (d1) with the values of d2 merge and the two dictionaries’ items are updated.
  7. Next, we should print d1.
  8. Then, using the update method, we update d2 with values of d1, basically merging the two dictionary items as updated elements.
  9. Next, we print d2.
  10. Then, we create a new variable (called new) and assign the dictionary with d3,d4 parameters using the exponential operator (basically we update with the methods from the d3 and d4 dictionary).
  11. Finally, we print the new variable.

Code

d1 = {1:"cucumber",2:"peas",3:"carrot"}
print(d1)
d3 = d1
d2 = {4:"Pineapple",5:"Mango",6:"Apple"}
d4 = d2
d1.update(d2)
print(d1)
d2.update(d1)
print(d2)
new = {**d3,**d4}
print(new)

RELATED TAGS

merging
communitycreator
RELATED COURSES

View all Courses

Keep Exploring