progress

~/problems / Iterators & parsers / Parsers and interpreters

URL Query Parameter Parsing

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~20 min Airbnb

A search page receives URLs like https://stays.example/search?city=Lisbon&guests=2#map and needs the parameters as a dict.

Implement parse_query(url: str) -> dict[str, str | list[str]], following these rules in order:

  1. Ignore everything from the first # on.
  2. The query string is everything after the first ?; no ? means {}.
  3. Split it on &, skipping empty pieces.
  4. Split each piece at its first = into key and value (the value may contain =); no = means the value "".
  5. Decode key and value separately, after splitting: + is a space, % plus two hex digits (either case) is that character. Inputs only use escapes below %80. A % not followed by two hex digits stays as is.
  6. Skip pieces whose decoded key is empty.
  7. A key seen once maps to its value; a key seen more than once maps to a list of its values, in order.
parse_query("https://stays.example/search?city=Lisbon&guests=2#map")
# {"city": "Lisbon", "guests": "2"}

parse_query("/s?amenity=wifi&amenity=pool&q=sea+view&note=a%3Db%26c&flex")
# {"amenity": ["wifi", "pool"], "q": "sea view", "note": "a=b&c", "flex": ""}

parse_query("/s?&&=oops&x=1=2&disc=100%&y")
# {"x": "1=2", "disc": "100%", "y": ""}

parse_query("/about#faq?x=1")     # {}    the ? is inside the fragment

⭐ Bonus: a speed test with a URL of 50,000 parameters earns a star if the work is linear: append to a key's list instead of rebuilding it.

Show hint

str.partition splits at the first occurrence and tells "a" apart from "a=". Decode in one left-to-right pass.

Topic: Parsers and interpreters. Tokenize, recursive descent, S-expressions, evaluation and type inference.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc