← Back to Gists

Merge dicts safely

📝 Python
ryan_adams
ryan_adams · 4d ago
This snippet merges two dictionaries, preserving existing keys and avoiding overwrites, using `{dict1, dict2}` with dict2 taking priority.
Python
def mergedictssafely(dict1, dict2): merged = dict1.copy() for key, value in dict2.items(): if key not in merged: merged[key] = value return merged

Comments

1
That unpacking trick is clean but only works in Python 3.5+. I once spent an hour debugging a production script that silently dropped keys because someone used `{a, b}` on a Python 3.4 runtime.