root = d = {'node1': {'node2': True}}
n = 10
keys = ["node{}".format(i) for i in range(1, n+1)]
for k in keys[:-1]:
# Overwrite the True with a dictionary or create a dictionary,
# not sure the point of the True values in this problem.
if k not in d or not isinstance(d[k], dict):
d[k] = {}
# Recurse into the nested dictionary
d = d[k]
# Set the final key to True.
d[keys[-1]] = True
print(root)
输出:
相关问题 更多 >
编程相关推荐