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
defaults = {"theme": "light"}
mine = defaults.copy()
mine["theme"] = "dark"
print(defaults, mine)
Output
{'theme': 'light'} {'theme': 'dark'}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']}
TrueVersion history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
dict.update()· Add or overwrite keys from another mapping, an iterable of pairs, or keyword arguments, in place.dict()· Create a dictionary: a mapping of keys to values. Build it from keyword arguments, pairs or another mapping.- Python Dictionaries · tutorial