I have a simple function which translates nested dictionary to one level dictionary and renames keys like "level1_level2_key". I tried to write some simple doctest and found that i'm getting keys from the second test in third.
So there are some problems with contexts + recursion.
def go_through(node, base_name='', response={}):
"""
Normalize python dictionay to one level
>>> go_through({'key': 1, })
{'key': 1}
>>> go_through({'key': 1, 'sub_key': { 'key1': 1 }})
{'key': 1, 'sub_key_key1': 1}
>>> go_through({'key': 1, 'sub_key': { 'key2': 1 }})
{'key': 1, 'sub_key_key': 1}
"""
for key, item in node.items():
sub_key = '%s_%s' % (base_name, key)
if sub_key.startswith('_'):
sub_key = sub_key[1:]
if type(item) == dict:
new_response = go_through(item, sub_key, response=response)
for k in new_response.keys():
response[k] == new_response[k]
else:
if not key in response.keys():
response[sub_key] = item
return response
Could someone suggest solution for this (except - doctests are harmful etc)?
File "./test.py", line 80, in __main__.go_through
Failed example:
go_through({'key': 1, 'sub_key': { 'key2': 1 }})
Expected:
{'key': 1, 'sub_key_key': 1}
Got:
{'sub_key_key2': 1, 'key': 1, 'sub_key_key1': 1}
**********************************************************************
1 items had failures:
1 of 3 in __main__.go_through
***Test Failed*** 1 failures.