Python 3 reference · Dictionary Methods

Python Dictionary copy() Method

Return a shallow copy of the dictionary: a new dict with the same keys and values (nested values are shared).

Python 3 Since 3.0

Syntax

dict.copy()

Return value

A new dict.

Examples

Copy before changingTry it yourself
defaults = {"theme": "light"}
mine = defaults.copy()
mine["theme"] = "dark"
print(defaults, mine)

Output

{'theme': 'light'} {'theme': 'dark'}
Nested values are sharedTry it yourself
import copy
config = {"tags": ["a"]}
shallow = config.copy()
shallow["tags"].append("b")
print(config)  # shared list!
print(copy.deepcopy(config) == config)

Output

{'tags': ['a', 'b']}
True

Version history

VersionChange
Python 3.0Added