man k/dictionaries

Dictionaries and grouping in K

lib / K 10 mindraft

checked against: ngn/k b9eeb91

What is a dictionary in K, and what does it cost to use one?

In Python or Go the answer is a hash table. K is an array language, and in ngn/k, one dialect of it, a dictionary is two lists of the same length side by side: the keys and the values. Everything else follows from that. A lookup is a search of the key list. Arithmetic between two dictionaries lines up their keys. And =x (group), the primitive that answers “where does each value occur?”, returns a dictionary in which the order of the keys means something.

This article reads the ngn/k C source at commit b9eeb91 (2026-07-21) and checks each claim with a small experiment run with k file.k. K reads right to left, and most primitives are a single character, so under every block there is a plain reading of the symbols in it.

Two lists with a type tag

d:`apple`pear`fig!3 5 2
!d
.d
d`pear
d`kiwi

How to read it:

  • `apple`pear`fig is a list of three symbols (interned strings).
  • x!y makes a dictionary from a list of keys x and a list of values y. d: names it.
  • !d returns the keys and .d the values.
  • d`pear looks up the key `pear. Putting a value next to a dictionary indexes it, like d[`pear].

Saved as basics.k, together with the updates in the next section, it starts with these four lines:

$ k basics.k
`apple`pear`fig
3 5 2
5
0N

The C side is just as small. Dyadic ! on two lists checks that the lengths match and calls am, which allocates an object of type tm with exactly two children, the key list and the value list (2.c line 109, m.c line 42). Most primitives that take a dictionary start by calling kv, which splits it back into keys and values (m.c line 60). The type table in a.h labels tm with the example X! (a.h lines 103 to 105).

A missing key gives 0N, the integer null. Indexing a list past its end returns the null of the list’s type, and a failed lookup is turned into exactly that kind of index (a.c line 11).

Indexing a dictionary calls fnd(keys, y), the same function as dyadic ? (find), and then indexes the values with the position it returns (a.c line 29). For keys of 2, 4 or 8 bytes, which covers integers and symbols, fnd runs a loop that walks the key list from the start until it hits the value (f.c lines 5 to 13, lines 40 to 47). There is no hash table anywhere in the file. One-byte keys, characters included, get a 256-entry position table instead, filled once per call (f.c line 39).

So the cost of a lookup grows with the number of keys. This program looks up 1,000 keys that are all missing, the worst case, 100 times over, in key lists of three sizes:

q:1+2*!1000
k:2*!1000
\t:100 k?q
k:2*!10000
\t:100 k?q
k:2*!100000
\t:100 k?q
k:2*!10000
\t:100 k?100000+!1000

How to read it:

  • !n is the list 0, 1, …, n−1. 2*!1000 is the even numbers below 2,000, and q:1+2*!1000 the odd numbers below 2,000, none of which are keys.
  • x?y (find) returns the position of each item of y in x, or 0N.
  • \t:100 expr is an interpreter command: run expr 100 times and print the total in milliseconds.
$ k find.k
32
304
2978
0

Ten times the keys, ten times the time: about 0.3 ms per 1,000 lookups per 1,000 keys. The last line is a shortcut in the C. 2*!10000 fits in 2-byte integers, and a value that doesn’t fit in the key list’s width can’t be in it, so fnd returns 0N without scanning (f.c lines 10 to 12).

Other Ks make other choices. The q documentation, for the language of kdb+, says its grouped attribute g# “causes kdb+ to create and maintain an index (hash table)”, and lists Find among the searching functions that benefit from attributes. ngn/k has no attributes.

Updating a key that isn’t there

A dictionary is updated in place with d[k] followed by an assignment, and d[k]+:1 adds 1. If k is new, there is nothing to add to. These lines continue the same file, basics.k, after the lookups above:

d[`kiwi]+:1;d
d[`plum]*:4;d
d[`lime]&:7;d
d[`date],:9;d

How to read it:

  • d[k]+:1 is modified assignment: apply + with 1 to the entry for k and store the result. *: multiplies, &: takes the minimum, ,: appends.
  • ; separates two expressions, and the second, d, prints the dictionary.
`apple`pear`fig`kiwi!3 5 2 1
`apple`pear`fig`kiwi`plum!3 5 2 1 4
`apple`pear`fig`kiwi`plum`lime!3 5 2 1 4 7
`apple`pear`fig`kiwi`plum`lime`date!(3;5;2;1;4;7;,9)

Every new key starts from the identity element of the verb. + starts from 0, so the first +:1 gives 1. * starts from 1, & from the largest integer, and , from an empty list, which is why `date holds the list ,9 and the values are no longer a flat list of integers. The amend code looks the keys up, appends the missing ones, and appends ie(verb, values) for each (a.c line 79). ie reads its answer from a constant: 0x2332211004 holds one 4-bit entry per verb, an index into the five candidates 0, 1, the largest integer, the smallest non-null integer and the null (a.c lines 4 to 6).

That is what makes the counting idiom {x[y]+:1;x}/ work without a default value. Every one of those x[y] is still a search of the keys, so counting n values with k distinct ones that way is O(n · k).

Arithmetic lines the keys up

a:`x`y!1 2
b:`y`z!10 20
a+b
a*b

How to read it: two dictionaries with one key in common, added and multiplied.

`x`y`z!1 12 20
`x`y`z!1 20 20

The result has the union of the keys. A key missing on one side is filled with 0 for + and -, and with 1 for * and %, before the verb runs (w.c lines 29 to 31). `x comes out as 1 in both, because 1+0 and 1×1 are both 1.

Group returns a dictionary

=x (group) maps each distinct item of x to the positions where it occurs. Counting each group, #'=x, is the K way to count occurrences, and a dictionary can be graded like a list.

w:"mississippi"
=w
#'=w
>#'=w
<#'=w

How to read it:

  • "mississippi" is a string, a list of characters.
  • =w groups it. #x is the length of x, and ' (each) applies # to every value of the dictionary, keeping the keys.
  • > (grade down) on a dictionary orders it by value, largest first, and returns the keys. < (grade up) does the same from the smallest.
$ k group.k
"misp"!(,0;1 4 7 10;2 3 5 6;8 9)
"misp"!1 4 4 2
"ispm"
"mpis"

The keys "misp" are in the order each letter first appears. The q docs promise the same for q’s group: “The order of the keys is the order in which they appear in x.” In ngn/k it comes out of three different implementations, chosen by the width of the items (o.c lines 39 to 43):

  • 1-byte items (characters, small integers): one pass counts each of the 256 possible values and records each value the first time it is seen. A second pass drops every position into its group. The record of first sightings is the key order.
  • 2-byte items: the same, with tables of 65,536 entries.
  • 4-byte items: a line of K, compiled once when it is first needed. 8-byte integers, floats, symbols and general lists get a near copy of it. The 4-byte version is {$[x;x[*'g]!g@:<g:(&~(~*s)=':s:x i)_i:<x;x!0#,!0]}.

The K line sorts first and restores the order afterwards. Read right to left:

  • i:<x grades x: the positions that put it in ascending order. s:x i is the sorted values.
  • =':s compares each value with the one before it (': is each-prior). The first value is compared with the seed on the left, ~*s (not the first value), so it never matches. ~ negates, so the result is 1 wherever a new value starts, and & turns that into the positions of those starts.
  • _i cuts the list of positions at those starts, giving one group per distinct value. Since the grade is stable, the positions inside each group are ascending.
  • g@:<g sorts the groups by grading them. Groups compare like words, item by item, and their first items are all different, so this orders them by the first position of each value: first-appearance order.
  • x[*'g]!g takes the value at the first position of each group (*' is first of each) as the keys, and the groups as the values.
  • $[x;...;x!0#,!0] handles the empty list.

The step that keeps the order is also the expensive one. Grading the groups is a general merge sort over lists, comparing them through the generic comparison function, while the first grade is a radix sort over 4-byte integers. This program times each stage on 100,000 random integers below 100,000:

x:100000?100000
T:{[s;f;a]t:`t 0;r:f a;`0:s,($(`t 0)-t)," us";r}
i:T["grade x        ";<:;x]
s:T["sort values    ";{x y}[x];i]
b:T["find the edges ";{&~(~*x)=':x};s]
g:T["cut positions  ";{x_y}[b];i]
q:T["grade groups   ";{<x};g]
d:T["whole of =x    ";=:;x]

How to read it:

  • 100000?100000 is 100,000 random integers below 100,000.
  • T takes a label s, a function f and an argument a. It reads the clock (`t 0 is the time in microseconds), applies f to a, prints the label and the elapsed time with `0:, and returns the result so the next stage can use it. $ turns a number into a string.
  • Each line runs one stage of the K line above on the previous stage’s result. <: and =: are grade and group used as one-argument functions, and {x y}[x] fixes the first argument of {x y}, which indexes x with y.
$ k parts.k
grade x        1094 us
sort values    68 us
find the edges 303 us
cut positions  5278 us
grade groups   14484 us
whole of =x    21636 us

Each stage runs once, and the last line times all of =x separately, so the stages don’t add up to it exactly. Two thirds of the time goes into putting the keys in first-appearance order.

Grading a dictionary is short in C: split it with kv, grade the values, index the keys with the result (o.c line 29). The grades are stable, so "ispm" lists i before s: both occur four times and i comes first among the keys. Grade down is implemented as reverse, grade up, reverse, which keeps it stable too (o.c line 38). q’s idesc behaves the same way on a dictionary: its documentation shows idesc `a`c`b!1 2 3 returning `b`c`a.

Curious facts

  • Symbols of up to four bytes are stored inside the 64-bit value itself. Longer ones are interned into a single 64 KiB string table, searched with strcmp each time a longer symbol is made (m.c lines 71 to 73). x:`$`c$97++26 26 26 26\!200000 makes 200,000 distinct four-letter symbols without trouble. Twenty thousand five-letter ones stop the interpreter with 'SYMS.
  • Group on a number is unrelated to group on a list. =3 is the 3×3 identity matrix, written in K as =/:/2#,!: (o.c line 39).
  • ?x (distinct) on a list of 2-, 4- or 8-byte numbers that fits in one memory page, 16,384 bytes on an Apple Silicon Mac, uses {x@&(x?x)=!#x}: keep each item whose first position is its own position. With a linear find that is a quadratic search. Longer lists are sorted first (o.c lines 45 to 47).
  • ' (each) on a dictionary applies the function to the values and keeps the keys, which is why #'=w is still a dictionary (w.c line 15).

History

The K wiki describes ngn/k as “an implementation of K6 created by ngn” and dates its start to April 9, 2017. Per the same page, the code moved to Codeberg in 2021, was frozen on May 24, 2022, and was announced as no longer supported in January 2024. The readme at the commit used here says the same and points to a maintained fork, codeberg.org/growler/k. Every source file carries the header “(c) 2019-2024 ngn”.

Sources

ngn/k at commit b9eeb91e0343ef6029f59d55dd98f82667b9bd59:

Other documentation:

ls k/