cswork / libraryOpen practice workspace

Coding questions · Citadel

Implement Left Join Using Python Dictionaries Efficiently

This question evaluates competency in tabular data manipulation and join semantics using Python dictionaries, emphasizing understanding of hashing-based lookups and algorithmic complexity such as O(N+M).

Orders

+---------+----------+--------+
| order_id| customer | amount |
+---------+----------+--------+
|    101  |    C1    |  250   |
|    102  |    C2    |  300   |
|    103  |    C3    |  150   |

Customers

+----------+-----------+
| customer | city      |
+----------+-----------+
|   C1     |  Seattle  |
|   C3     |  Boston   |
|   C4     |  Austin   |
Scenario

Performing a left join in pure Python without external libraries.

Question

Write Python code (no third-party packages) to left-join two lists of dictionaries on key "customer"; discuss an O(N+M) hashing solution.

Hints

Contrast nested loops with dict-based look-ups; handle missing matches gracefully.

Left Join Orders to Customers by Customer ID

You are given two tables: Orders and Customers. Write a SQL query to perform a LEFT JOIN from Orders to Customers on the "customer" key, returning all orders along with the customer's city when available. If a customer is missing from Customers, the city should be NULL.

Return columns: order_id, customer, amount, city.

Table orders

columntypeconstraints
order_idINTPRIMARY KEY
customerVARCHAR(10)NOT NULL
amountINTNOT NULL

Sample data:

amountcustomerorder_id
250C1101
300C2102
150C3103

Table customers

columntypeconstraints
customerVARCHAR(10)PRIMARY KEY
cityVARCHAR(50)NOT NULL

Sample data:

citycustomer
SeattleC1
BostonC3
AustinC4

Expected output

One row per order (all rows from orders), with city populated when the customer exists in customers; otherwise city is NULL.

amountcitycustomerorder_id
250SeattleC1101
300NULLC2102
150BostonC3103

Hints

  1. Use a LEFT JOIN to keep all rows from orders.
  2. Join condition is orders.customer = customers.customer.
  3. Customers without a match should yield NULL for city.