我有一个简单的函数,它将嵌套字典转换为一个级别的字典,并重命名像" level1_level2_key"这样的键。我试着写一些简单的doctest,发现我从第二次测试得到了第三次的密钥。
因此上下文+递归存在一些问题。
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
有人可以为此建议解决方案(除了 - doctests有害等)?
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.