Dictionaries
Creating Dictionaries
A dictionary maps a list of keys to a list of values of the same length. Dictionaries are q's general-purpose key-value structure, and every table is built from one.
Syntax
keys!valuesd:`a`b`c!10 20 30a| 10
b| 20
c| 30Dictionary Literal Syntax
A more concise, self-describing form (kdb+ 4.1+) names each key directly. Keys created this way are always symbols:
d:([a:10;b:20;c:30])Dot Apply
! is just another function, so a dictionary can also be built with dot apply, passing (keys;values) as a single argument list:
d:(!) . (`a`b`c;10 20 30)Key Vector Types
Whether keys can have mixed types depends on the key vector used to build the dictionary:
| Key vector | Mixed key types allowed? |
|---|---|
| Simple list (all keys the same type, e.g. symbols) | No |
| General list (keys of different types) | Yes |
Dictionary literal ([...]) | No — symbols only |
This matters when joining dictionaries: , requires the key vectors on each side to have compatible types, otherwise the join fails with 'type (e.g. joining a symbol-keyed dictionary with a character-keyed one).
Generating Keys with Roll (?)
The Roll operator ? is a quick way to generate random dictionary keys and values:
10?100.0 / 10 random floats, with replacement
-10?100 / 10 distinct random longs from 0-99, without replacementA negative left argument samples without replacement, guaranteeing unique keys — but the domain must be large enough to supply that many distinct values, or the call fails with 'length.
Practice Questions
Test your understanding with 3 hands-on questions