def reducefn(*dicts): #collects multiple arguments and stores in dicts for dic in dicts: #go over each dictionary passed in for k,v in dic.items(): #go over key,value pairs in the dic print(k,v) reducefn({'practical': 1, 'volume': 1, 'physics': 1} ,{'practical': 1, 'volume': 1, 'chemistry': 1})
Gives out
>>> physics 1 practical 1 volume 1 chemistry 1 practical 1 volume 1
Now about your implementation:
def reducefn(k, v):
The above function has two arguments. The arguments passed to the function are accessed via k and v respectively. Thus, calling reducefn({"key1":"value"},{"key2":"value"}) causes k assigned {"key1":"value"} and v assigned {"key2":"vlaue"} .
When you try to call it like this: reducefn(dic1,dic2,dic3,...) you pass more than the allowed number of parameters, as defined by the reducefn declaration / signature.
for k,val in (k,v):
Now, assuming that you went through two dictionaries to reducefn , both k and v will be dictionaries. The for loop above would be equivalent:
>>> a = {"Name":"A"} >>> b = {"Name":"B"} >>> for (d1,d2) in (a,b): print(d1,d2)
Which gives the following error:
ValueError: need more than 1 value to unpack
This is because you do this when the for loop is called:
d1,d2=a
You can see that we get this error when we try to do it in REPL
>>> d1,d2=a Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> d1,d2=a ValueError: need more than 1 value to unpack
We could do this:
>>> for (d1,d2) in [(a,b)]: print(d1,d2) {'Name': 'A'} {'Name': 'B'}
Assigns a tuple (a,b) to d1,d2 . This is called unpacking and will look like this:
d1,d2 = (a,b)
However, in our loop for k,val in (k,v): that would not make sense, since we would end up with k , and val representing the same thing as k , v . Instead, we need to go through the key value pairs in the dictionaries. But, seeing that we need to cope with n dictionaries, we need to rethink the definition of a function.
Hence:
def reducefn(*dicts):
When you call the function as follows:
reducefn({'physics': 1},{'volume': 1, 'chemistry': 1},{'chemistry': 1})
*dicts collects arguments in such a way that dicts ends as:
({'physics': 1}, {'volume': 1, 'chemistry': 1}, {'chemistry': 1})
As you can see, the three dictionaries passed to the function were collected in a tuple. Now we iterate over the tuple:
for dic in dicts:
So, now, at each iteration, dic is one of the dictionaries we went through, so now we go ahead and print out pairs of keys, values ββin it:
for k,v in dic.items(): print(k,v)