Skip to content

Instantly share code, notes, and snippets.

@zealinux
Last active January 11, 2019 08:49
Show Gist options
  • Save zealinux/030ca06fa115de58b8d7facbfccb2a3e to your computer and use it in GitHub Desktop.
Save zealinux/030ca06fa115de58b8d7facbfccb2a3e to your computer and use it in GitHub Desktop.
Such as merge two or more dicts to one
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