Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kdb q - lookup in nested list

Tags:

kdb

q-lang

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!

like image 991
tenticon Avatar asked Feb 12 '18 14:02

tenticon


People also ask

How to flatten a multi-level nested list in kdb+?

Below example shows a multi-level nested list in kdb+, we can use over (/) in conjunction with “raze” to converge on a flat list. But instead of having to use “raze” multiple times to flatten the nested list, we can instead use raze combined with /. Raze will keep executing until it has flattened the entire nested structure.

What is the depth of a nested list?

Nested lists have item (s) that are themselves lists. The number of levels of nesting for a list is called its depth. Informally, the depth measures how much repeated indexing is necessary to arrive at only atoms. Atoms have depth 0 and simple lists have depth 1. The notation of complex lists is reflected in nested parentheses.

What is kdb+/Q?

Kdb+/q originated as an obscure academic language but over the years, it has gradually improved its user friendliness. K (1993, crisp version of A+, developed by A. Whitney) Why? − If you need a single solution for real-time data with analytics, then you should consider kdb+.

How do you retrieve items from a nested list in SQL?

Get the item at index 1 from L, and from it retrieve the item at index 2, and from it retrieve the item at index 0. There is an alternate notation for repeated indexing into the constituents of a nested list. The last retrieval can also be written as, Assignment via index also works at depth.


2 Answers

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.

like image 181
Ryan McCarron Avatar answered Sep 26 '22 01:09

Ryan McCarron


Why are you making this difficult on yourself? Use a table!

q)t:([] c:`tech`tech`fin`fin; sym:`aapl`msfw`gs`jpm)
q)first exec c from t where sym=`jpm

You can of course do what you're asking:

first where `jpm in'd

but this doesn't extend well to vectors while the table-approach does!

q)exec c from t where sym in `jpm`gs
like image 42
geocar Avatar answered Sep 24 '22 01:09

geocar