Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. dict.copy() / dict() / Dict Merge

dict.copy() / dict() / Dict Merge

Since: Python 3.9(2020)

This page covers how to copy, create, and merge dictionaries. Python 3.9 and later also support a simpler merge using the | operator.

Syntax

new_dict = dictionary.copy()

# Creates a new dictionary from keyword arguments or an existing dictionary.
new_dict = dict(key=value, ...)
new_dict = dict(dictionary)

# Merges multiple dictionaries using the unpacking operator.
merged = {**dict1, **dict2}

# Merges two dictionaries using the | operator (Python 3.9+).
merged = dict1 | dict2

Functions and Operators

Function / OperatorDescription
dict.copy()Creates and returns a shallow copy of the dictionary. Changes to the original do not affect the copy, but nested mutable values are still shared.
dict(key=value)Creates a dictionary from keyword arguments. Keys must be strings.
dict(dictionary)Creates a new dictionary from an existing dictionary or iterable.
{**dict1, **dict2}Creates a new dictionary by merging multiple dictionaries using the unpacking operator. If a key appears in both, the value from the later dictionary takes precedence.
dict1 | dict2Returns a new dictionary that merges two dictionaries (Python 3.9+). If a key appears in both, the value from the right-hand dictionary takes precedence.
dict1 |= dict2Merges the contents of dict2 into dict1 in place (Python 3.9+).

Sample Code

dict_copy_merge.py
original = {'name': 'Yagami Iori', 'age': 20}
copied = original.copy()
copied['name'] = 'Kusanagi Kyo'
print(original['name']) # Prints 'Yagami Iori' — the original is unchanged.
print(copied['name']) # Prints 'Kusanagi Kyo'.

# Create a dictionary with dict().
d1 = dict(name='Terry Bogard', age=24)
print(d1) # Prints {'name': 'Terry Bogard', 'age': 24}.

# Merge dictionaries using the unpacking operator.
base = {'color': 'blue', 'size': 'M'}
extra = {'size': 'L', 'weight': 60}
merged = {**base, **extra}
print(merged) # Prints {'color': 'blue', 'size': 'L', 'weight': 60}.

# Merge with the | operator (Python 3.9+).
d2 = {'x': 1, 'y': 2}
d3 = {'y': 99, 'z': 3}
result = d2 | d3
print(result) # Prints {'x': 1, 'y': 99, 'z': 3}.

# Merge in place with |=.
settings = {'theme': 'dark', 'lang': 'ja'}
overrides = {'lang': 'en', 'font': 'mono'}
settings |= overrides
print(settings) # Prints {'theme': 'dark', 'lang': 'en', 'font': 'mono'}.

Running the code produces the following output:

python3 dict_copy_merge.py
Yagami Iori
Kusanagi Kyo
{'name': 'Terry Bogard', 'age': 24}
{'color': 'blue', 'size': 'L', 'weight': 60}
{'x': 1, 'y': 99, 'z': 3}
{'theme': 'dark', 'lang': 'en', 'font': 'mono'}

Common Mistakes

Common Mistake 1: Nested Data Is Shared After a Shallow Copy

dict.copy() and {**d} both create shallow copies. If a value is a mutable object such as a list or dictionary, both the copy and the original share the same reference.

import copy

original = {
    'Yagami Iori': {'power': 950, 'skills': ['Dark Thrust', 'Yaotome']},
    'Kusanagi Kyo': {'power': 900, 'skills': ['108 Shiki', 'Orochi Nagi']},
}

# a shallow copy shares nested objects
shallow = original.copy()
shallow['Yagami Iori']['power'] = 999 # the original is also changed
print(original['Yagami Iori']['power']) # 999 (unintended change)

The same logic can also be written as:

deep = copy.deepcopy(original)
deep['Yagami Iori']['power'] = 999
print(original['Yagami Iori']['power']) # 950 (unchanged)

Common Mistake 2: The | Operator Requires Python 3.9 or Later

The | merge operator for dictionaries requires Python 3.9 or later and is not available in earlier versions.

team_a = {'Yagami Iori': 950, 'Kusanagi Kyo': 900}
team_b = {'Terry Bogard': 880, 'Blue Mary': 820}
merged = team_a | team_b # Python 3.9+

# Works on Python 3.8 and earlier too
merged = {**team_a, **team_b}
# or
merged = dict(team_a)
merged.update(team_b)

Notes

dict.copy() creates a shallow copy. If the values are immutable objects such as strings or numbers, modifying one copy does not affect the other. However, if a value is a mutable object such as a list or another dictionary, the reference is shared between the two copies. Use copy.deepcopy() when a deep copy is required.

There are several ways to merge dictionaries. The {**d1, **d2} syntax works from Python 3.5 onward and can merge three or more dictionaries at once. Python 3.9 and later allow the more readable d1 | d2 syntax. In either case, if a key exists in both dictionaries, the value from the later dictionary takes precedence. Be careful not to overwrite values unintentionally.

For creating dictionaries with comprehensions, see Dictionary Comprehensions.

If you find any errors or copyright issues, please .