Search code examples
dictionarykdb

Applying a Function to a dictionary


I am new to KDB and am currently getting to grips with dictionaries.I have a dictionary of the format

UK|34 55 6 16
Italy|44 78 43 12
Iran|21 4 2

How would I create and apply a function to my dictionary so that an average may be calculated for each key?


Solution

  • q)avgFunc:{sum[x]%count x} /create function
    q)/apply the function to each dictionary value
    q)avgFunc each  `UK`Italy`Iran!(34 55 6 16;44 78 43 12;21 4 2)
    UK   | 27.75
    Italy| 44.25
    Iran | 9
    

    https://code.kx.com/q/ref/each/

    The each adverb applies the function to each value of the dictionary