Dictionaries · Creating Dictionaries · Practice Question
Keys of same type
Question
A developer is building lookup dictionaries for a trading application.
Do all keys in a q dictionary need to have the same type?
Solution
Not necessarily — it depends on the key vector:
dict:(`AAPL;101;10.5;"IBM")!(100;200;300;400)Result:
`AAPL| 100
101 | 200
10.5 | 300
"IBM"| 400Because the keys are a general list, the console shows each key in its q form: the symbol with its backtick and the string in quotes.
Explanation
Here the keys list is initially defined as a general list
(`AAPL;101;10.5;"IBM")Its items include a symbol, a long, a float and a string (character vector). Because the keys are a general list, we can join this dictionary with other dictionaries whose keys are of any type:
dict:(`AAPL;101;10.5;"IBM")!(100;200;300;400)
new:(`TSLA;205;1.1;"AST")!(200;100;800;700)
dict,new`AAPL| 100
101 | 200
10.5 | 300
"IBM"| 400
`TSLA| 200
205 | 100
1.1 | 800
"AST"| 700However, if dict is created with a simple (typed) list of symbols as its keys, the join fails:
dict:(`AAPL`TSLA`MSFT`GOOG)!(100;200;300;400)
dict,new'typeIf we swap the order, so that the left dictionary has the general list of keys, the join works:
new,dict`TSLA| 200
205 | 100
1.1 | 800
"AST"| 700
`AAPL| 100
`MSFT| 300
`GOOG| 400