Back to Updating & Merging Dictionaries

Dictionaries · Updating & Merging Dictionaries · Practice Question

Merging Dictionaries

Sign in to track your progress

Question

A trading system receives position data from two sources.

The primary source contains the current positions:

primary:`AAPL`MSFT`GOOG!100 0N 300

A backup source contains additional position information:

backup:`MSFT`GOOG`NVDA!250 0N 400

Merge the dictionaries using both:

  1. Join (,)
  2. Coalesce (^)

What is the difference between the results?

Solution

Using Join:

primary,backup

Result:

AAPL| 100
MSFT| 250
GOOG|
NVDA| 400

Using Coalesce:

primary^backup

Result:

AAPL| 100
MSFT| 250
GOOG| 300
NVDA| 400

Explanation

For the shared keys MSFT and GOOG, Join always takes backup's value — GOOG becomes null (0N, which the console shows as a blank) since that's backup's value for GOOG, overwriting primary's 300. NVDA exists only in backup, so it is simply added. Coalesce only takes backup's value when primary's is null — GOOG stays 300 since primary's value is non-null, while MSFT and NVDA (null or absent in primary) take backup's values either way.