树中的动态设置值

时间:2019-04-17 10:29:02

标签: python dictionary

如果我有动态键路径['key1','key2',...,'keyN'],如何设置树的值?

from collections import defaultdict

def tree(): return defaultdict(tree)

t = tree()


def set_value(t, keys_path, value):
    # TODO smth

set_value(t, ['key1', 'key2', ..., 'keyN'], 'value')
assert t['key1']['key2']...['keyN'] = 'value'

问题不是如何创建嵌套字典,就像在Nested defaultdict of defaultdict中回答的那样,而是从键列表直接访问字典的深度,因为t['key1']['key2']...['keyN']不能按原样实现

0 个答案:

没有答案