Created
April 20, 2022 17:14
-
-
Save FerusAndBeyond/c70bcd434beda50b4c7feae4a41386cb to your computer and use it in GitHub Desktop.
Python dict merging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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