Sign in to run and submit your work
Reading is open to everyone. Running code and saving drafts need an account so your work is yours and comes back on your next visit.
or
CODE WORKSPACE
Before a load runs, you want to know how many distinct entities are in the batch — so you collect the distinct values of a composite key. Some of the fields in the key hold lists or nested objects.
Write unique_keys(records, key_fields). It returns the distinct keys, each as a list of the field values, in the order they were first seen.
Function to write
unique_keys(records: list[dict], key_fields: list[str]) -> list[list]A list of distinct keys, each a list of the field values in `key_fields` order.
How to approach it
Add the dedupe yourself, with a set. The tags case is where it argues back.
Sample cases
+ 2 held back until you submit
a repeated order line
The ordinary case: two identical lines collapse to one key, first-seen order kept.
Input
Argument 1
| order_id | sku |
|---|---|
| 1042 | A1 |
| 1042 | A1 |
| 1043 | B7 |
Argument 2
[
'order_id',
'sku'
]Returns
[
[
1042,
'A1'
],
[
1043,
'B7'
]
]a field holding a list
A list is unhashable, so the naive set raises. Two equal lists are still one key.
Input
Argument 1
[
{
'order_id': 1042,
'tags': [
'x',
'y'
]
},
{
'order_id': 1042,
'tags': [
'x',
'y'
]
}
]Argument 2
[
'order_id',
'tags'
]Returns
[
[
1042,
[
'x',
'y'
]
]
]no records
Nothing in, nothing out — and no attempt to read a field from a record that is not there.
Input
Argument 1
[] (empty list)
Argument 2
[
'order_id'
]Returns
[] (empty list)
Constraints
key_fields, in the order the fields were given.None, which is a legitimate key value.Worked example
Two records both have order_id 1042 and tags of ['x', 'y']. They are one key, and the answer is [[1042, ['x', 'y']]].
The obvious dedupe builds the key as a list and puts it in a set, which raises TypeError: unhashable type: 'list' on the first record. A list can be mutated after insertion, so a set could never find it again — the refusal is the container protecting its own contract rather than an arbitrary restriction.
What this tests
That only immutable values can be hashed, and that turning a value into a hashable stand-in is a conversion you write rather than something the language does. The dict case adds the second half: equality has to be order-independent to be useful.
unique_keys(records: list[dict], key_fields: list[str]) -> list[list]Submit for review to find out what your query gets right, what it gets wrong, and how it compares with the best working query for this exercise.
This scenario runs a full workspace — editor, canvas and results side by side. It needs a laptop or desktop to be usable. Open this page on a bigger screen to start building.