Sanny
Sanny

Reputation: 303

KDB: In-place delete from dictionary

To upsert an element into the dictionary, I do

q) d[`x]:12345

This modifies existing dictionary and the operation cost is close to O(1) or O(log N) depending on the underlying implementation (hash table or tree) (I don't know in fact).

However, to remove a key I must use:

q) d:(enlist `x) _ d

Which is at least O(N) because it copies the full dictionary without deleting items in O(N) then assigns is to d in O(1) because of pointer.

This looks like delete operation discrimination! Maybe in-place delete is poorly documented but exists somewhere?

Upvotes: 4

Views: 3615

Answers (3)

Alexander Belopolsky
Alexander Belopolsky

Reputation: 2268

Two more options include apply:

.[`d;();_;`x]

functional delete

![`d;();0b;enlist`x]

The last form is useful if you want to delete multiple keys in one go. E.g.,

![`d;();0b;`x`y]

Upvotes: 8

SJT
SJT

Reputation: 1097

Four forms support deleting in place.

Drop through assignment allows you to drop a single key ‘in place’.

q)show d:`a`b`c`x!(1;2 3;4;5)
a| 1
b| 2 3
c| 4
x| 5
q)d _: `x
q)d
a| 1
b| 2 3
c| 4

Apply will allow you to parameterise the key:

q)show d:`a`b`c`x!(1;2 3;4;5)
a| 1
b| 2 3
c| 4
x| 5
q).[`d;();_;`x]
q)d
a| 1
b| 2 3
c| 4

delete like all Q-SQL templates similarly supports ‘in place’ through call-by-reference, and also allows you to drop multiple keys:

q)show d:`a`b`c`x!(1;2 3;4;5)
a| 1
b| 2 3
c| 4
x| 5
q)delete x,b from `d
`d
q)d
a| 1
c| 4

Functional delete supports multiple keys and allows you to parameterise the keys. (Use parse to see the functional form of the Q-SQL template.)

q)show d:`a`b`c`x!(1;2 3;4;5)
a| 1
b| 2 3
c| 4
x| 5
q)parse "delete x,b from d"
!
`d
()
0b
,`x`b
q)![`d;();0b;`x`b]
`d
q)d
a| 1
c| 4

Links above are to the kdb+ documentation site code.kx.com.

Upvotes: 6

Sean O'Hagan
Sean O'Hagan

Reputation: 1697

2 ways:

d _:`x

or

delete x from `d

Upvotes: 5

Related Questions