Python Basics

Merge Dictionaries in Python

Combining dictionaries is useful when applying defaults, configuration overrides, or updates from another data source.

What is Merge Dictionaries?

Combining dictionaries is useful when applying defaults, configuration overrides, or updates from another data source.

Merge Python dictionaries with the modern union operator.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
defaults = {"theme": "dark", "language": "en"}
preferences = {"language": "vi", "font_size": 16}

settings = defaults | preferences
print(settings)

Expected output

{'theme': 'dark', 'language': 'vi', 'font_size': 16}

How it works

The union operator creates a new dictionary. When keys overlap, the value from the dictionary on the right wins.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →