Update dictionary value for q lang (kdb +)

How can I update values ​​in q dictionaries using the functional way?

Example:

x: `1`2`3;
d: x!x;
show[d];
// d -> 
// 1 | 1
// 2 | 2
// 3 | 3
// TODO change d: 
show[d];
// d -> 
// 1 | 11
// 2 | 22
// 3 | 3
+4
source share
4 answers

You can change the dictionary this way:

// @[dictionary name; list of keys; ?; list of values];
@[d; `1`2; :; `11`22];
+5
source

A functional dictionary update is also possible with the standard change / install syntax (using ":") as follows:

q)x:1 2 3

q)d:x!x

q)d
1| 1
2| 2
3| 3

q)f:{d[x]:y}
q)f[2;7]

q)d
1| 1
2| 7
3| 3

This also works for vectors provided that they have the same length:

q)f[1 2;5 6]
q)d
1| 5
2| 6
3| 3
+3
source

Another way:

q)x:1 2 3;
q)d:x!x;
q)d
  1| 1
  2| 2
  3| 3
q)d,: enlist[2]!enlist[5];
q)d
  1| 1
  2| 5
  3| 3
q)d,: (2 3)!(7 7);
q)d
  1| 1
  2| 7
  3| 7
+2
source

You can use a simple change for the key you want to change.

q)d[1 2]+:10
q)d
1| 11
2| 12
3| 3

It is equivalent

d[1 2]:d[1 2]+10

or

d[1 2]:11 12

There is no real need to use the function to change the values ​​in the dictionary.

0
source

Source: https://habr.com/ru/post/1660802/


All Articles