Search code examples
csvdictionaryoutputexport-to-csvkdb+

kdb/q How can I save a Dictionary?


I have a dictionary and I'm trying to save using kdb/q. To save my dictionary, I try the same method as I would a table:

save `output.csv

However, my output dictionary (type 99h) gives me an error:

q))save `output.csv
   'output
   [4]  save `output.csv
        ^

I think this is because the notation only works for tables and not dictionaries. Can anyone help me with how to do this, or if it isn't possible, how I can change a dictionary to be a table?

Here is what my dictionary looks like:

output -> type 99

an example of the dictionary

Output using `:out.csv set output

`:out.csv set output


Solution

  • This should work. save is flexible enough to write a keyed table to csv. https://code.kx.com/q/ref/save/

    q)output:([Name:`Tim`Bob`Ant;Time:02:20 01:12 03:30;ID:`9h`8a`2w]Score:100 212 998;Comment:("";"Late";"Over"))
    q)type output
    99h
    q)save`output.csv
    `:output.csv
    q)read0`:output.csv
    "Name,Time,ID,Score,Comment"
    "Tim,02:20,9h,100,"
    "Bob,01:12,8a,212,Late"
    "Ant,03:30,2w,998,Over"
    

    The error message you've pasted would indicate that output doesn't exist in your current context. Are you perhaps trying to save a local table rather than a global?

    q){output2:([Name:`Tim`Bob`Ant;Time:02:20 01:12 03:30;ID:`9h`8a`2w]Score:100 212 998;Comment:("";"Late";"Over"));save`output2.csv}[]
    'output2