Dictionaries · Updating & Merging Dictionaries · Practice Question
Merging Dictionaries
Question
A trading system receives position data from two sources.
The primary source contains the current positions:
primary:`AAPL`MSFT`GOOG!100 0N 300A backup source contains additional position information:
backup:`MSFT`GOOG`NVDA!250 0N 400Merge the dictionaries using both:
- Join (
,) - Coalesce (
^)
What is the difference between the results?
Solution
Using Join:
primary,backupResult:
AAPL| 100
MSFT| 250
GOOG|
NVDA| 400Using Coalesce:
primary^backupResult:
AAPL| 100
MSFT| 250
GOOG| 300
NVDA| 400Explanation
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.