Develop myReduceByKey Function¶
Develop a function by name myReduceByKey which takes a collection of tuples and a function as arguments. Each element in the collection should have exactly 2 attributes. Function should do the following:
- Iterate through the collection of tuples.
- Group the data by first element in the collection of tuples and apply the function using the argument passed. Argument should have necessary arithmetic logic.
- Return a collection of tuples, where first element is unique and second element is aggregated result.
In [1]:
d = {}
In [2]:
type(d)
Out[2]:
dict
In [3]:
d[2] = 199.99
In [4]:
d
Out[4]:
{2: 199.99}
In [5]:
2 in d
Out[5]:
True
In [6]:
if 2 in d: d[2] = d[2] + 250.0
In [7]:
d
Out[7]:
{2: 449.99}
In [8]:
4 in d
Out[8]:
False
In [9]:
if 4 in d: d[4] = d[4] + 100
else: d[4] = 100
In [10]:
d
Out[10]:
{2: 449.99, 4: 100}
In [11]:
def myReduceByKey(c_p, f):
d = {}
for e in c_p:
if e[0] in d:
d[e[0]] = f(d[e[0]], e[1])
else:
d[e[0]] = e[1]
return list(d.items())