How to Merge Dictionaries in Python

Aug 30, 2024

Merging Dictionaries in Python

Introduction

  • Presenter: Abhishek
  • Topic: Merging two dictionaries in Python

Merging Dictionaries (Python 3.5 and Higher)

  • Method: Use the unpacking operator (**)
  • Syntax:
    sales = {**sales1, **sales2}  
    
  • This feature was introduced in Python 3.5.
  • It allows for quick merging of dictionaries in a single line.
  • Recommendation: Read the Python 3.5 documentation for more details.

Merging Dictionaries (Python Versions Lower than 3.5)

  • Method: Use the copy() and update() methods.
  • Syntax:
    sales = sales1.copy()  
    sales.update(sales2)  
    
  • This method is for users who are on older versions of Python.

Example and Demo

  • Executed code to show how to merge two dictionaries.
  • Result: Combined dictionary with values from both sales1 and sales2.

Quiz Time

  • Task: Create a new dictionary called web_courses.
    • Keys: html, hx, jengle
    • Values: 3000, 4000, 5000
  • Next Step: Merge web_courses with an existing dictionary containing Python or programming courses.

Conclusion

  • Encouragement to revisit the video if there are difficulties with the exercise.
  • Invitation to ask questions in the comments for further clarification.
  • Sign off for the next topic.