How to Merge Two Dictionaries, Objects or Maps (Shallow vs Deep Merge)
Merge Python dictionaries, JavaScript objects and Java maps in one line, decide which value wins on conflict, combine values instead of overwriting them, and avoid the shared-nested-object bug of shallow merges.
By Software Side Hustles Editorial Team · Published · Updated · 4 min read
Quick answer: Python 3.9+ merged = a | b, JavaScript const merged = { ...a, ...b }, Java var merged = new HashMap<>(a); merged.putAll(b);. In all three, keys in b overwrite keys in a, and the merge is shallow — nested dictionaries or objects are shared, not copied.
Merging by language
| Language | New merged copy | Merge into existing | Who wins on conflict |
|---|---|---|---|
| Python 3.9+ | a | b | a |= b or a.update(b) | right side (b) |
| Python 3.5+ | {**a, **b} | a.update(b) | right side |
| JavaScript | { ...a, ...b } | Object.assign(a, b) | right side |
| Java | new HashMap<>(a) then putAll(b) | a.putAll(b) | argument (b) |
| Go 1.21+ | copy a, then maps.Copy(dst, b) | maps.Copy(a, b) | source (b) |
| C# | loop, or LINQ Concat + GroupBy | foreach (var kv in b) a[kv.Key] = kv.Value; | whatever you assign last |
How do I merge two dictionaries in Python?
defaults = {"theme": "light", "page_size": 20}user = {"page_size": 50}
settings = defaults | user # {'theme': 'light', 'page_size': 50}settings = {**defaults, **user} # same result, works on 3.5+defaults.update(user) # mutates defaults — usually not what you wantThe "defaults, then overrides" pattern is the most common reason to merge, and the order matters: put the values that should win last.
update() returns None, so settings = defaults.update(user) leaves settings as None — the same trap as list.sort().
Combining values instead of overwriting
When both dictionaries hold counts or lists, overwriting loses data. Combine explicitly:
from collections import CounterCounter({"a": 1, "b": 2}) + Counter({"b": 3}) # Counter({'b': 5, 'a': 1})
merged = dict(a)for k, v in b.items(): merged[k] = merged.get(k, 0) + vNote that adding Counters drops keys whose total is zero or negative; use update() on a Counter if you need to keep them.
How do I merge two objects in JavaScript?
const defaults = { theme: "light", pageSize: 20 };const user = { pageSize: 50 };
const settings = { ...defaults, ...user }; // { theme: "light", pageSize: 50 }const same = Object.assign({}, defaults, user);Object.assign(defaults, user); // mutates defaultsSpreading null or undefined is allowed and contributes nothing — { ...a, ...maybeNull } — which is handy for optional overrides. Arrays are merged differently: [...a, ...b] concatenates; use [...new Set([...a, ...b])] for a union.
For Map objects, spread the entries: new Map([...m1, ...m2]).
How do I merge two Maps in Java?
Map<String, Integer> merged = new HashMap<>(a);merged.putAll(b); // b wins
Map<String, Integer> counts = new HashMap<>(a);b.forEach((k, v) -> counts.merge(k, v, Integer::sum)); // add values on conflictWith streams, Collectors.toMap throws on duplicate keys unless you provide a merge function:
Map<String, Integer> merged = Stream.of(a, b) .flatMap(m -> m.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y));Without the third argument you get IllegalStateException: Duplicate key ... (attempted merging values ...).
The shallow merge trap
Every one-liner above is a shallow merge. Top-level keys are copied, but nested objects are the same objects:
const base = { db: { host: "localhost", port: 5432 } };const merged = { ...base };merged.db.port = 6543;console.log(base.db.port); // 6543 — base was changed tooAnd a shallow merge replaces nested objects rather than combining them:
a = {"db": {"host": "localhost", "port": 5432}}b = {"db": {"port": 6543}}a | b # {'db': {'port': 6543}} — host is goneThis is the classic configuration bug: an environment override for one nested value wipes out its siblings.
How do I deep merge nested dictionaries or objects?
A small recursive function is usually clearer than adding a dependency:
def deep_merge(a: dict, b: dict) -> dict: out = dict(a) for k, v in b.items(): if isinstance(v, dict) and isinstance(out.get(k), dict): out[k] = deep_merge(out[k], v) else: out[k] = v return out
deep_merge({"db": {"host": "localhost", "port": 5432}}, {"db": {"port": 6543}})# {'db': {'host': 'localhost', 'port': 6543}}const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function deepMerge(a, b) { const out = { ...a }; for (const [k, v] of Object.entries(b)) { out[k] = isPlainObject(v) && isPlainObject(out[k]) ? deepMerge(out[k], v) : v; } return out;}Decide how arrays should behave — replace (as above) or concatenate — and write it down; libraries such as lodash merge make different choices. If the merged input comes from users (for example, JSON request bodies), refuse the keys __proto__, constructor and prototype in JavaScript deep merges to avoid prototype pollution.
Frequently asked questions
Which value wins when both dictionaries have the same key?
The one merged last: b in a | b, {**a, **b}, { ...a, ...b } and a.putAll(b).
How do I merge a list of dictionaries?
Python: functools.reduce(operator.or_, dicts, {}) or {k: v for d in dicts for k, v in d.items()}. JavaScript: Object.assign({}, ...objects).
Is {**a, **b} slower than a | b?
Not meaningfully. Pick | on Python 3.9+ for readability.
How do I merge without mutating either input?
Use the "new merged copy" column above. For nested data, combine a deep merge with a deep copy — see deep copy vs shallow copy.
Where this skill pays off
"Merge the user's settings over the defaults" is a request AI assistants handle constantly, and the shallow-merge bug is easy to miss when the example config has only one level. Being able to say precisely why an answer fails is what AI evaluation platforms pay developers for — start with what makes one coding solution better than another.