Report this

What is the reason for this report?

Python update method

Posted on January 15, 2025

team,in python dictionary I want to add a dictionary with the existing dictionary



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hey! 👋

To do that you can use the .update() method:

# Existing dictionary
dict1 = {'a': 1, 'b': 2}

# New dictionary to add
dict2 = {'c': 3, 'd': 4}

# Using update() to merge
dict1.update(dict2)

print(dict1)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

If you’re using Python 3.9 or later, you can also use the | operator:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Merging with |
merged_dict = dict1 | dict2

print(merged_dict)

- Bobby

Heya,

In Python, you can add a new dictionary to an existing dictionary by updating it. Here’s how you can do it:

Example:

# Existing dictionary
existing_dict = {
    "name": "Alice",
    "age": 25
}

# New dictionary to add
new_dict = {
    "city": "New York",
    "country": "USA"
}

# Add the new dictionary to the existing one
existing_dict.update(new_dict)

print(existing_dict)

Output:

{'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}

Explanation:

  • The update() method takes the key-value pairs from new_dict and adds them to existing_dict.
  • If a key in new_dict already exists in existing_dict, its value will be overwritten.

Let me know if you need help with any specific use case!

Heya, @d79445eef4054c269ef68e2eb17af3

In general .update() and the | operator (in Python 3.9+) are the most common ways to directly modify and merge dictionaries. These were covered in Bobby’s reply with good examples.

You can also merge dictionaries by passing them to the dict() constructor:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Using the dict constructor to merge
merged_dict = dict(dict1, **dict2)

print(merged_dict)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

This works similarly to dictionary unpacking and is also compatible with older versions of Python (before Python 3.5).

Regards

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.