Develop myJoin Function¶
Develop a function by name myJoin which takes two collections of tuples as arguments. Each element in each of the collection should have exactly 2 attributes. Function should do the following:
- Build the dict for the first collection.
- Iterate through the second collection and look up into the dict.
- Return a collection of tuples, where first element is join key and second element is a nested tuple with values from the dict and the second collection.
In [1]:
l1 = [
(1, 'COMPLETE'),
(2, 'CLOSED'),
(3, 'COMPLETE')
]
In [2]:
dict(l1)
Out[2]:
{1: 'COMPLETE', 2: 'CLOSED', 3: 'COMPLETE'}
In [3]:
l2 = [
(1, 100),
(2, 129.99),
(2, 140),
(2, 300),
(3, 150),
(3, 160)
]
In [4]:
item = l2[0]
In [5]:
item[0] in dict(l1)
Out[5]:
True
In [6]:
def myJoin(c1, c2):
c1_dict = dict(c1) # dict with first element as key and second element as value
results = [] # Initializing empty list
for c2_item in c2:
if c2_item[0] in c1_dict:
results.append((c2_item[0], (c1_dict[c2_item[0]], c2_item[1])))
return results
In [7]:
orders = [(1, 'COMPLETE'), (2, 'CLOSED')]
In [8]:
order_items = [(1, 129.99), (1, 149.99), (2, 250.0), (3, 100.0)]
In [9]:
myJoin(orders, order_items)
Out[9]:
[(1, ('COMPLETE', 129.99)), (1, ('COMPLETE', 149.99)), (2, ('CLOSED', 250.0))]