Create a copy of the defaults, and update it with d
; if all keys in d
are strings, you can do so with one dict()
call:
d = dict(default_dict, **d)
For dictionaries with non-string keys, you'd use two steps:
d = default_dict.copy()
d.update({'name': 'James', 'age': 65})
or you could use a loop to update d
with any keys not present using dictionary views; this is not as fast however:
d = {'name': 'James', 'age': 65}
d.update((k, default_dict[v]) for k in default_dict.viewkeys() - d)
Replace viewkeys
with keys
in Python 3.
If you are using Python 3.5 or newer, you can use similar syntax to create a new dictionary:
d = {**default_dict, 'name': 'James', 'age': 65}
The key-value pairs of default_dict
are applied first, followed by whatever new keys you set; these will override the old. See PEP 448 - Additional Unpacking Generalizations in the 3.5 What's New documentation.
Any of the methods creating a new dictionary can update an existing dictionary simply by wrapping in a dict.update()
call. So the first could update d
in-place with:
d.update(dict(default_dict, **d))