Inner join of two CSV datasets
I was asked this
No reports yet. Sign in to say where you were asked it.
Two systems export CSV data that you need to combine. Implement:
def join_datasets(customer_file: list[str], processor_file: list[str], field: str) -> list[str]
Each dataset is a list of lines. The first line is a header of comma-separated column names. Every other line is a data row with one value per column. Both headers contain the column field, but it can be at a different position in each file. Values never contain commas or quotes.
Return an inner join on field, as a list of CSV lines:
- The first line is the customer header followed by the processor header.
- Then, for each customer row (in input order), add one line for every processor row whose
fieldvalue is equal (in processor order). Each line holds all customer values followed by all processor values. - Customer rows with no match, and processor rows with no match, do not appear.
- A key can repeat in either file. Every matching pair produces a line.
Constraints: up to 10^5 rows per file and up to 20 columns. Comparisons are exact string matches.
Example
customer_file = ["cust_id,name,country", "c1,Ada,US", "c2,Lin,SG", "c3,Ola,NG"]
processor_file = ["amount,cust_id", "500,c1", "120,c3", "75,c1", "900,c9"]
field = "cust_id"
Output:
["cust_id,name,country,amount,cust_id",
"c1,Ada,US,500,c1",
"c1,Ada,US,75,c1",
"c3,Ola,NG,120,c3"]
c2 has no charge and c9 has no customer, so neither appears. c1 has two charges, so it appears twice.
Later parts may ask for a left join that keeps unmatched customer rows, and for options that change which rows are kept.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
