Skip to content

Instantly share code, notes, and snippets.

@lukmdo
Created February 26, 2017 18:44
Show Gist options
  • Save lukmdo/66417c11883e16b857162a208faaff00 to your computer and use it in GitHub Desktop.
Save lukmdo/66417c11883e16b857162a208faaff00 to your computer and use it in GitHub Desktop.
For non inlplace dict setdefault
"""
For non inlplace dict setdefault.
"""
base_dict = {'a': 'a-ORIG', 'b': 'b-ORIG', 'd': 'd-ORIG'}
defaults = {'a': 'A', 'b': None, 'c': 0}
overrides = defaults
# Update by override. Like:
# - base_dict.update(overrides) -> new dict BUT `dict.update` is inplace
# - base_dict + overrides -> new dict BUT unsupported operand
print(dict(base_dict, **overrides)) # update by override i.e.
{'a': 'A', 'b': None, 'c': 0, 'd': 'd-ORIG'}
# Update by setdefault. Like:
# - base_dict.set_defaults(defaults) -> new dict BUT there is only inplace `dict.setdefault`
# - defaults.update(base_dict) -> new dict BUT `dict.update` is inplace
# - base_dict | defaults -> new dict BUT unsupported operand
print(dict(defaults, **base_dict))
{'a': 'a-ORIG', 'b': 'b-ORIG', 'c': 0, 'd': 'd-ORIG'}
# SUMMARY (only by literals, no dedicated method[s] ...)
# - py2+py3: dict(base_dict, **overrides) or dict(defaults, **base_dict)
# - py3 (>=3.5): {**base_dict, **overrides} or {**defaults, **base_dict}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment