Skip to content

Instantly share code, notes, and snippets.

@FerusAndBeyond
Created April 20, 2022 17:14
Show Gist options
  • Save FerusAndBeyond/c70bcd434beda50b4c7feae4a41386cb to your computer and use it in GitHub Desktop.
Save FerusAndBeyond/c70bcd434beda50b4c7feae4a41386cb to your computer and use it in GitHub Desktop.
Python dict merging
a = { "a": 5, "b": 5 }
b = { "c": 5, "d": 5 }
c = { **a, **b }
assert c == { "a": 5, "b": 5, "c": 5, "d": 5 }
# order matters!
# the last added will overwrite the first added
c = { **a, **b, "a": 10 }
assert c == { "a": 10, "b": 5, "c": 5, "d": 5 }
b["a"] = 10
c = { **a, **b }
assert c == { "a": 10, "b": 5, "c": 5, "d": 5 }
# this doesn't work when initializing with dict(...)
c = dict(**a, **b)
# => TypeError: type object got multiple values for keyword argument 'a'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment