Dictionaries · Lookup By Value · Practice Question
Inverting a Dictionary
Inverting a Dictionary
Question
A trading system stores the list of instruments available on each exchange in the following dictionary:
d:`NYSE`NASDAQ`LSE!(
`AAPL`MSFT`IBM;
`AAPL`NVDA`TSLA;
`IBM`VOD
)(In a script, the closing parenthesis must be indented by at least one space so q reads it as part of the same statement.)
Create a new dictionary whose:
- Keys are instrument symbols
- Values are the exchange(s) on which the instrument trades
Expected output:
AAPL| `NYSE`NASDAQ
MSFT| ,`NYSE
IBM | `NYSE`LSE
NVDA| ,`NASDAQ
TSLA| ,`NASDAQ
VOD | ,`LSESolution
r:group (!) . flip raze key[d] ,'' value[d]Result:
AAPL| `NYSE`NASDAQ
MSFT| ,`NYSE
IBM | `NYSE`LSE
NVDA| ,`NASDAQ
TSLA| ,`NASDAQ
VOD | ,`LSEExplanation
The original dictionary maps:
Exchange -> SymbolsThe goal is to invert this relationship to produce:
Symbol -> ExchangesThe expression:
key[d] ,'' value[d]pairs each exchange with every symbol contained in its value list. ,'' is Join applied with Each twice: once across the exchanges, then across each exchange's symbols. The result is one list of pairs per exchange:
(`NYSE;`AAPL)
(`NYSE;`MSFT)
(`NYSE;`IBM)
(`NASDAQ;`AAPL)
(`NASDAQ;`NVDA)
(`NASDAQ;`TSLA)
(`LSE;`IBM)
(`LSE;`VOD)Flattening and flipping these pairs:
flip raze key[d] ,'' value[d]produces two lists of equal length — the exchanges and the symbols:
NYSE NYSE NYSE NASDAQ NASDAQ NASDAQ LSE LSE
AAPL MSFT IBM AAPL NVDA TSLA IBM VODFinally, (!) . applies ! to those two lists, giving a dictionary from exchange to symbol (with repeated keys), and group on a dictionary groups its keys by value — producing a dictionary whose keys are symbols and whose values are the exchanges each symbol trades on.
This technique is useful whenever a dictionary represents a one-to-many relationship and you need to reverse the lookup direction. Examples include:
- Exchange → Symbols → Symbol → Exchanges
- Sector → Instruments → Instrument → Sectors
- Portfolio → Holdings → Holding → Portfolios
- Market → Tradable Products → Product → Markets
Ordering the Result
The order of keys in the resulting dictionary depends on the order in which symbols are first encountered during the grouping operation.
If you want the keys to appear in ascending order, there are several approaches.
Option 1: Sort Keys and Values Explicitly
k:iasc key r
key[r][k]!value[r][k]Result:
AAPL| `NYSE`NASDAQ
IBM | `NYSE`LSE
MSFT| ,`NYSE
NVDA| ,`NASDAQ
TSLA| ,`NASDAQ
VOD | ,`LSEOption 2: Re-index Using a Sorted Key List
t:asc key r
t#rResult:
AAPL| `NYSE`NASDAQ
IBM | `NYSE`LSE
MSFT| ,`NYSE
NVDA| ,`NASDAQ
TSLA| ,`NASDAQ
VOD | ,`LSEThe second approach is often preferred because it is shorter and more directly expresses the intent: reorder the dictionary according to a sorted list of keys.