I'm trying to learn how to write functional code with Python and have found some tutorials online. Please note that I know Python is not a promoter for functional programming. I just want to try it out. One tutorial in particular gives this as an exercise:
Write a function flatten_dict to flatten a nested dictionary by joining the keys with . character.
So I decided to give it a try. Here is what I have and it works fine:
def flatten_dict(d, result={}, prv_keys=[]):
for k, v in d.iteritems():
if isinstance(v, dict):
flatten_dict(v, result, prv_keys + [k])
else:
result['.'.join(prv_keys + [k])] = v
return result
I'd like to know whether this is the best way to solve the problem in python. In particular, I really don't like to pass a list of previous keys to the recursive call.