gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:44:13 25 4
gpt4 key购买 nike

<分区>

我正在尝试展平嵌套字典,同时还根据另一个嵌套字典交换其键。我假设没有一个分支具有相同的 key 。例如:

在:

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"}}

预计结束时间:

{“一”:3,“二”:23,“三”:“abc”,“四”:21,“五”:95}

我正在使用 iteritems hack 尝试使此代码与 Python 2.7 兼容,但我正在 3.4 上进行测试。我添加了一堆打印语句来跟踪执行;递归调用似乎从未真正发生过。

try:
dict.iteritems
except AttributeError:
# Python 3
def itervalues(d):
return iter(d.values())
def iteritems(d):
return iter(d.items())
else:
# Python 2
def itervalues(d):
return d.itervalues()
def iteritems(d):
return d.iteritems()

def flatten_dict(mapping, values_dict):
print("Function called with {} and {}".format(mapping, values_dict))
for (key, value) in iteritems(mapping):
print("K: {} V: {} Mapping: {}".format(key, value, mapping))
if isinstance(value, dict):
# Note that we have to flatten the values_dict as we flatten
# mapping dict, hence the [key]
print("Going to recurse")
print("Passing {} and {}".format(value, values_dict[key]))
flatten_dict(value, values_dict[key])
else:
print("Going to yield {}, {}".format(value, values_dict[key]))
yield (value, values_dict[key])

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"}}

for (x,y) in flatten_dict(mapping_dict_test, values_dict_test):
print(x, y)

输出:

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) 链接到的副本使用可变默认参数,已知在这些情况下它的行为违反直觉 (2) 它较旧,下面给出的答案显示了 Python 3.3 解决方案我没有看到旧问题。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com