Created
December 31, 2010 02:57
-
-
Save jparise/760661 to your computer and use it in GitHub Desktop.
merge_dicts(d1,d2) - safely merges the contents of d2 into d1
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
def merge_dicts(d1, d2): | |
"""Safely merges the contents of the dictionary d2 into dictionary d1. | |
Unlike dict.update(), this is a non-destructive operation: a KeyError is | |
raised if one of d2's keys already exists in d1. | |
""" | |
# Based on timing tests, it's faster to scan for conflicts upfront and | |
# then perform a bulk update. This presumes that, generally speaking, | |
# the destination dictionary d1 will be larger (in item count) than d2. | |
for key in d2.iterkeys(): | |
if key in d1: | |
raise KeyError("destination dict already contains key '%s'" % key) | |
d1.update(d2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment