How do I force a default value of key in dictionary when key is not preset. For example, say I have list of dictionaries
t
key
delayedassetMainType
assetSubTypecusip
12
34
67
8!(“LPL”;0b;“EQUITY”;“ADR”;“50186V102”;9.03;9.4;9.25;1f;," ";,“P”;1101592f)
key
delayedassetMainType
cusip1
23
45
67
8!(“NFLX”;0b;“EQUITY”;“64110L106”;396.05;396.5;396.05;2f;4f;,“Q”;,“P”;5.890427e+07)
key
delayedassetMainType
cusip1
23
45
67
8!(“LAZR”;0b;“EQUITY”;“550424105”;13.16;13.25;13.19;4f;1f;,“P”;,“P”;1.450048e+07)
First in the list doesn’t have key ``1 so vector operation like xkey would be a problem because key length is not same. So other way is to write something below in cond “?'” operation to get default value 99
{ca:key
12
34
56
78 in key x;val:t[
key1
23
45
67
8];?[ca;val;enlist enlist 99]} each t
But this gives error `length. I can assure that length of ca, val is same and is 9.
May be my solution is convoluted that is why I am asking the question in simplified example
q)d:a
b`c!(“”;2;3)
q)d[`d]
“”
If `d is not available in dict d, I want to return 99 instead of “”
Hi,
You can define a dictionary with the default values that you would like to assign and then use the fill operator to assign these values when the key is missing or the value is null.
q)ddef:enlist[`d]!enlist 99 q)d:`a`b`c!(“”;2;3) q)(ddef^d)`d 99
Fill operator, fills keyword replace nulls in a vector | Reference | kdb+ and q documentation - Kdb+ and q documentation (kx.com)
I’ve made a post with some notes which helps present code in questions:
https://community.kx.com/t5/General/Creating-q-code-block-with-syntax-highlighting-in-a-message/td-p/11094
This blog on JSON parsing may also have some useful tips for you as it covers some areas of nested data with irregular keys
https://kx.com/blog/kdb-q-insights-parsing-json-files/
An example for your ask is to use a prototype dictionary of default values
// Prototype of default values if lookup fails q)p:a
bc
d!(“X”;99;99;99) q)p a| “X” b| 99 c| 99 d| 99 // Actual dictionary q)d:a
bc!("";2;3) q)d a| "" b| 2 c| 3 // Failed lookup uses null of type of first key // a is first key, it is type char, null char is "" q)d
d “” // Prototype can be used by appending your dict to it q)(p,d)d 99 q)(p,d)
b 2 // Handles vectors of keys nicely q)(p,d)d
b`a 99 2 “”