遍历字典以获取依赖项(也许使用递归?)

Traverse a dictionary to get dependencies (using recursion perhaps?)

这是我收到的 json 个文件的类型:

{'n1': [5, 'number'],
 'n2': [6, 'number'],
 'm1': ['n1 x n2', 'n1 times n2'],
 'm2': ['X - m1', 'subtract n1 times n2'],
 'n3': [4, 'quarter'],
 'n4': [8, 'number'],
 'm3': ['n4 / n3', 'quarter of number n4'],
 'm4': ['m2 = m3', 'obtain m3']}

我想要的是得到'm4',然后一路往回遍历,这样'm2=m3'就变成'X - 5*6 = 8/4 我认为这可能与递归有关,但实际上并没有任何经验。 必须在 Python.

内完成

我收到的 json 具有不同的复杂性甚至更多的依赖性,但这是模板。 谢谢!

这是你想要的吗?:

table = {
    'n1': [5, 'number'],
    'n2': [6, 'number'],
    'm1': ['n1 x n2', 'n1 times n2'],
    'm2': ['X - m1', 'subtract n1 times n2'],
    'n3': [4, 'quarter'],
    'n4': [8, 'number'],
    'm3': ['n4 / n3', 'quarter of number n4'],
    'm4': ['m2 = m3', 'obtain m3']
}

string = 'm4'
while True:
    for key, (value, description) in table.items():
        if key in string:
            string = string.replace(key, str(value))
            break
    else:
        break

print(string)

输出:

X - 5 x 6 = 8 / 4

请注意,如果您有循环依赖或递归依赖,此算法将永远不会结束