You are given a string data that holds a sequence of key-value pairs separated by semicolons (;). Each pair has the form key=value. Parse the string and return a list of [key, value] pairs sorted by key.
Empty segments, which come from consecutive or trailing semicolons, are ignored. Every non-empty segment is a well-formed key=value pair, and keys are unique.
Function Signature
def parse_data(data: str) -> list[list[str]]:
Rules
-
Split the input on
;
. A segment that is empty after the split produces no pair.
-
Split each remaining segment at its
=
. The left side is the key and the right side is the value. Both are returned as strings, so
"30"
stays
"30"
.
-
Sort the pairs by key with plain string comparison (character code order). Digits come before uppercase letters, uppercase letters before
_
, and
_
before lowercase letters. For example,
"B"
sorts before
"a"
, and
"Name"
sorts before
"name_2"
.
-
If every segment is empty, return an empty list.
Constraints
-
1 <= len(data) <= 10^4
-
data
consists of key-value pairs separated by
;
.
-
Each non-empty segment has the form
key=value
.
-
Keys and values consist of letters, digits and
_
.
-
Keys are unique within the input.
Examples
Input: data = "name=alice;age=30;city=paris"
Output: [["age","30"],["city","paris"],["name","alice"]]
Splitting on ; gives three pairs. Sorted by key, age comes before city, which comes before name.
Input: data = "b=2;a=1;c=3"
Output: [["a","1"],["b","2"],["c","3"]]
The input order is b, a, c. Sorting by key gives a, b, c.
Input: data = "x=1;;Name=bob;name_2=z;"
Output: [["Name","bob"],["name_2","z"],["x","1"]]
The empty segment between the two adjacent semicolons and the empty segment after the trailing semicolon are skipped. N (code 78) sorts before n (code 110), and n sorts before x (code 120).