KX Community

Find answers, ask questions, and connect with our KX Community around the world.

Home Forums kdb+ Default dictionary value

  • Default dictionary value

    Posted by vijaykvishwa on February 2, 2022 at 12:00 am

    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`delayed`assetMainType`assetSubType`cusip`1`2`3`4`6`7`8!("LPL";0b;"EQUITY";"ADR";"50186V102";9.03;9.4;9.25;1f;," ";,"P";1101592f)
    `key`delayed`assetMainType`cusip`1`2`3`4`5`6`7`8!("NFLX";0b;"EQUITY";"64110L106";396.05;396.5;396.05;2f;4f;,"Q";,"P";5.890427e+07)
    `key`delayed`assetMainType`cusip`1`2`3`4`5`6`7`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`1`2`3`4`5`6`7`8 in key x;val:t[`key`1`2`3`4`5`6`7`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 “”

     

    vijaykvishwa replied 1 month, 1 week ago 3 Members · 2 Replies
  • 2 Replies
  • vkennedy

    Member
    February 2, 2022 at 12:00 am

    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)

  • rocuinneagain

    Member
    February 2, 2022 at 12:00 am

    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`b`c`d!("X";99;99;99) 
    q)p a| "X" b| 99 c| 99 d| 99 
    // Actual dictionary 
    q)d:`a`b`c!("";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 ""

     

     

Log in to reply.