在dict/tree展平时未调用Python(3.4)递归函数

2024-10-01 02:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在根据另一个嵌套dict交换其键的同时,使嵌套字典扁平化。我假设没有一个分支具有相同的键。E、 g.:

在:

values_dict_test = {"abs": 3, "cd": 23, "sdf": "abc", "gxr":
{"rea": 21, "bdf": 95}}
mapping_dict_test = {"abs": "one", "cd": "two", "sdf": "three", "gxr":
{"rea": "four", "bdf": "five"}}

预期输出:

{"one": 3, "two": 23, "three": "abc", "four": 21, "five": 95}

我正在使用iteritems黑客来尝试使这段代码与Python2.7兼容,但我在3.4上测试。我添加了一堆print语句来跟踪执行;似乎递归调用实际上从未发生过。在

^{pr2}$

输出:

Function called with {'cd': 'two', 'sdf': 'three', 'abs': 'one', 'gxr': {'rea': 'four', 'bdf': 'five'}} and {'cd': 23, 'sdf': 'abc', 'abs': 3, 'gxr': {'rea': 21, 'bdf': 95}}
K: cd V: two Mapping: {'cd': 'two', 'sdf': 'three', 'abs': 'one', 'gxr': {'rea': 'four', 'bdf': 'five'}}
Going to yield two, 23
two 23
K: sdf V: three Mapping: {'cd': 'two', 'sdf': 'three', 'abs': 'one', 'gxr': {'rea': 'four', 'bdf': 'five'}}
Going to yield three, abc
three abc
K: abs V: one Mapping: {'cd': 'two', 'sdf': 'three', 'abs': 'one', 'gxr': {'rea': 'four', 'bdf': 'five'}}
Going to yield one, 3
one 3
K: gxr V: {'rea': 'four', 'bdf': 'five'} Mapping: {'cd': 'two', 'sdf': 'three', 'abs': 'one', 'gxr': {'rea': 'four', 'bdf': 'five'}}
Going to recurse
Passing {'rea': 'four', 'bdf': 'five'} and {'rea': 21, 'bdf': 95}

(通常,我会使用values = {key: value for (key, value) in values_dict_gen},其中values_dict_gen是该函数返回的生成器。)

编辑:有利于重新打开,(1)duplicate linked to使用了一个可变的默认参数,在这些情况下它的行为与直觉相反(2)它更旧,下面给出的答案显示了我在老问题上没有看到的Python3.3解决方案。在


Tags: tocdabsonedictthreefourvalues
1条回答
网友
1楼 · 发布于 2024-10-01 02:32:20
flatten_dict(value, values_dict[key])

此调用在生成器内部执行与外部相同的操作;它创建生成器对象。它不会自动运行生成器并生成其项。如果要递归地使用生成器,则必须自己迭代:

^{pr2}$

或者在Python 3中:

yield from flatten_dict(value, values_dict[key])

相关问题 更多 >