kdb+q-lang

kdb q - lookup in nested list


Is there a neat way of looking up the key of a dictionary by an atom value if that atom is inside a value list ?

Assumption: The value lists of the dictionary have each unique elements

Example:

d:`tech`fin!(`aapl`msft;`gs`jpm) / would like to get key `fin by looking up `jpm
d?`gs`jpm / returns `fin as expected
d?`jpm    / this doesn't work unfortunately
$[`jpm in d`fin;`fin;`tech] / this is the only way I can come up with

The last option does not scale well with the number of keys

Thanks!


Solution

  • You can take advantage of how where operates with dictionaries, and use in :

    where `jpm in/:d
    ,`fin
    

    Note this will return a list, so you might need to do first on the output if you want to replicate what you have above.