Last active
January 11, 2019 08:49
-
-
Save zealinux/030ca06fa115de58b8d7facbfccb2a3e to your computer and use it in GitHub Desktop.
Such as merge two or more dicts to one
This file contains hidden or 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
def merge_dicts(*dict_args): | |
""" | |
Given any number of dicts, shallow copy and merge into a new dict, | |
precedence goes to key value pairs in latter dicts. | |
""" | |
result = {} | |
for dictionary in dict_args: | |
result.update(dictionary) | |
return result | |
# Test | |
x = {'a': 1, 'b': 2} | |
y = {'b': 3, 'c': 4} | |
z = merge_dicts(x, y) #=> {'a': 1, 'b': 3, 'c': 4} | |
# only in Python 3.5 up faster | |
z = {**x, **y} #=> {'a': 1, 'b': 3, 'c': 4} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment