cjm2671
cjm2671

Reputation: 19466

Cleanest way of joining a dictionary to a string?

Let's say I have

k: `a`b`c
v: 1 2 3

How can we make a string of the form:

a=1&b=2&c=3

Upvotes: 1

Views: 207

Answers (2)

terrylynch
terrylynch

Reputation: 13572

This is very situational but if you're only doing this for "display" purposes then you could make use of built-in .Q.s

q)ssr/[-2_.Q.s d;("| ";"\r\n");("=";"&")]
"a=1&b=2&c=3"

The output would be limited by your console size though, so for all practical purposes you would/should use kylebonnes answer.

EDIT: .Q.s2 gets you pretty close too:

q)"&"sv"="^.Q.s2 d
"a|=1&b|=2&c|=3"

EDIT2: based on your further disclosure that the purpose of this is to build query strings then I've a few other comments:

  1. You most likely want commas , instead of & then. You shouldn't normally use & in where clauses in queries.
  2. Neither mine nor kylebonnes solution would work for you in the event that you had symbols in the values of your dictionary, e.g.
d:`a`b`c!`one`two`three

and you're trying to build a query that says

where a=`one,b=`two,c=`three

in this case you'd have to try to use maybe .Q.s1 or else have logic to put the backticks in place.

  1. An alternative might be to build a functional form of a query but you're still going to be faced with similar problems
q)"?[t;",(-3!{(=;x;d x)}each key d),";0b;()]"
"?[t;((=;`a;1);(=;`b;2);(=;`c;3));0b;()]"
  1. Ultimately it isn't really good practice to be manufacturing complex query strings to send to a kdb server. Can you wrap your desired query up into a function and define the function on the server? Then your URL just has to call the function. Why can't you send a direct synchronous call to the kdb server, e.g.
h:hopen`::1234;
h({<function to generate query without having to string>};`a`b`c!1 2 3)

Upvotes: 0

kylebonnes
kylebonnes

Reputation: 936

The following lambda accomplishes what you want (accepting a dictionary as its argument):

{"&" sv "=" sv/: string flip (key;value)@\:x} `a`b`c!1 2 3

Upvotes: 3

Related Questions