2022.08.18 07:11 PM
hi, how can I swap key and list of values using q? Thanks!
python version: https://stackoverflow.com/questions/51740270/python-dictionary-swap-keyvalue-pair-when-values-exist-...
for example:
1 2 3!(4 5 3;6 7 3;4 1)
becomes
1 3 4 5 6 7!(enlist 3;1 2;1 3;enlist 1;enlist 2;enlist 2)
2022.08.18 07:34 PM
This achieves what you're looking for.
q)d:1 2 3!(4 5 3;6 7 3;4 1)
q)r:1 3 4 5 6 7!(enlist 3;1 2;1 3;enlist 1;enlist 2;enlist 2)
q){a!key[x]where each flip value(a:asc distinct raze x)in/:x} d
1| ,3
3| 1 2
4| 1 3
5| ,1
6| ,2
7| ,2
q)r~{a!key[x]where each flip value(a:asc distinct raze x)in/:x}d
1b
2022.08.18 07:34 PM
This achieves what you're looking for.
q)d:1 2 3!(4 5 3;6 7 3;4 1)
q)r:1 3 4 5 6 7!(enlist 3;1 2;1 3;enlist 1;enlist 2;enlist 2)
q){a!key[x]where each flip value(a:asc distinct raze x)in/:x} d
1| ,3
3| 1 2
4| 1 3
5| ,1
6| ,2
7| ,2
q)r~{a!key[x]where each flip value(a:asc distinct raze x)in/:x}d
1b
2022.08.18 08:21 PM - edited 2022.08.18 08:24 PM
Another method:
q){a!x a:asc key x:group(!). flip raze key[x],''value x}d
1| ,3
3| 1 2
4| 1 3
5| ,1
6| ,2
7| ,2
2022.08.19 06:28 AM
{key[x][i]!get[x]i:iasc key x:group(!). flip raze key[x],''get x}
indexing into the keys instead of doing a lookup a smidge faster
EMEA
Tel: +44 (0)28 3025 2242
AMERICAS
Tel: +1 (212) 447 6700
APAC
Tel: +61 (0)2 9236 5700
KX. All Rights Reserved.
KX and kdb+ are registered trademarks of KX Systems, Inc., a subsidiary of FD Technologies plc.