This is not a homework question. I came across this when I was attempting to answer a question on SO. It intrigued me. I searched online for a while and could not find anything. Here is the code:
def unravel(data, resultsdict={}):
for k in data:
if isinstance(data[k],dict):
unravel(data[k], resultsdict)
else:
resultsdict[k] = data[k]
return resultsdict
Run:
>>> print unravel({'a': 'b'})
{'a': 'b'}
>>> print unravel({'c': 'd'})
{'a': 'b', 'c': 'd'}
Why does the dictionary returned by the first method get used in the second call, in spite of the default argument resultsdict={}
?