Back to Updating & Merging Dictionaries

Dictionaries · Updating & Merging Dictionaries · Practice Question

Dictionary Value Replace

Sign in to track your progress

Replace Invalid Prices

Question

A market data system stores daily prices for several instruments in the following dictionary:

prices:`AAPL`MSFT`GOOG`TSLA!(
  101 105 107;
  (102;103);
  104 102 109;
  (105;102)
 )

A value of 102 has been identified as invalid and should be replaced with a null (0N).

Update the dictionary so that every occurrence of 102 is replaced by 0N.

Solution

key[prices]!{@[x;where x=102;:;0N]} each value prices

Alternative Solution

@[prices;key prices;:;@'[value[prices];where each 102=value[prices];:;0N]]

Result:

AAPL| 101 105 107
MSFT| 0N 103
GOOG| 104 0N 109
TSLA| 105 0N

Alternative Solution

key[prices]!@'[value prices;where each 102=/:value prices;:;0N]

Explanation

For each value list, where x=102 finds the positions equal to 102, and @[x;...;:;0N] nulls them out. Applying this each over value prices and re-pairing with key prices rebuilds the dictionary with 102 replaced throughout.

The alternative computes the matching positions for every value list in one pass with where each 102=/:value prices, then applies @' (each-both amend) to pair each value list with its own positions.