Given an array of records where each record is a list of two strings [key, value], group all records by their key.
Return a dictionary mapping each unique key to a list of all values associated with that key. The values for each key should appear in the same order as they appear in the input.
If the input array is empty, return an empty dictionary.
Function Signature
def group_by_key(records: list[list[str]]) -> dict[str, list[str]]:
Rules
-
Each record is a two-element list
[key, value]
.
-
Within each key's list, values keep their input order. A value that appears more than once under the same key is kept every time it appears.
-
Keys appear in the dictionary in the order they are first seen in the input.
Constraints
-
0 <= len(records) <= 10^5
-
len(records[i]) == 2
-
1 <= len(records[i][0]), len(records[i][1]) <= 100
-
records[i][0]
and
records[i][1]
consist of lowercase English letters and digits.
Examples
Input: records = [["dept","alice"],["dept","bob"],["eng","charlie"],["dept","dave"],["eng","eve"]]
Output: {"dept": ["alice", "bob", "dave"], "eng": ["charlie", "eve"]}
There are two unique keys. "dept" collects alice, bob and dave in that order, and "eng" collects charlie and eve.
Input: records = [["a","x"],["b","y"],["a","z"]]
Output: {"a": ["x", "z"], "b": ["y"]}
Key "a" appears at positions 0 and 2, so its values are x then z. Key "b" appears once.
Input: records = []
Output: {}
With no records there are no keys, so the result is an empty dictionary.