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:
- Ignore everything from the first
#on. - The query string is everything after the first
?; no?means{}. - Split it on
&, skipping empty pieces. - Split each piece at its first
=into key and value (the value may contain=); no=means the value"". - 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. - Skip pieces whose decoded key is empty.
- 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¬e=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.