KX Community

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

Home Forums kdb+ Why creating a table from a tale results in a list of dictionaries?

  • Why creating a table from a tale results in a list of dictionaries?

    Posted by kdb_newbie on June 19, 2023 at 12:00 am

    May I please ask why creating a table from a table results in a “list” of dictionaries?
    ([] tab) where tab is a table(98h) results in a list of dictionaries?

    Thank you!

    kdb_newbie replied 2 months, 1 week ago 2 Members · 1 Reply
  • 1 Reply
  • davidcrossey

    Member
    June 19, 2023 at 12:00 am

    A non-keyed table is just a list of dictionaries, flipped:

     

    q)tab:([]a:1 2 3;b:`a`b`c) 
    tab 
    a b 
    --- 
    1 a 
    2 b
    3 c 
    
    q)`a`b!(1 2 3;`a`b`c) 
    a| 1 2 3 
    b| a b c 
    
    q)flip `a`b!(1 2 3;`a`b`c) 
    a b 
    --- 
    1 a 
    2 b 
    3 c 
    
    q)tab~flip `a`b!(1 2 3;`a`b`c) 
    1b

     

    What you are doing here is creating a new table, with a column called tab. This new column has a record for each row of the original table as a dictionary

    q)tab:([]a:1 2 3;b:`a`b`c) 
    tab 
    a b 
    --- 
    1 a 
    2 b 
    3 c 
    
    q)([]tab) 
    tab 
    ----------- 
    `a`b!(1;`a) 
    `a`b!(2;`b) 
    `a`b!(3;`c)

    You can also enlist the table to create a single record in the new table:

    q)([] enlist tab) 
    tab 
    -------------------- 
    +`a`b!(1 2 3;`a`b`c)

    If you want to create a table from a table, typically you would utilise query filtering to select a subset of columns, or joins from another table. What is your use case here?

  • cillianreilly

    Member
    June 19, 2023 at 12:00 am

    First, remember that a table itself is just a list of dictionaries.

    q)0N!/:tab; 
    `col1`col2!(`a;1) 
    `col1`col2!(`b;2) 
    `col1`col2!(`c;3)

    So, when you tabulate a table, each entry in the original table (a dictionary) just becomes an entry in the new table column:

    q)([]tab) 
    tab 
    ----------------- 
    `col1`col2!(`a;1) 
    `col1`col2!(`b;2) 
    `col1`col2!(`c;3) 
    
    q)type ([]tab) 
    98h 
    
    q)type each tab 
    99 99 99h 
    
    q)type each([]tab) 
    99 99 99h

     

Log in to reply.