【发布时间】:2018-04-19 04:48:02
【问题描述】:
我已经搜索了文档并在许多队友的帮助下使用,但无法弄清楚如何通过(在我的情况下)测试函数将字典替换为 kwargs 提供的值:
模板字典:
{
"id": "id_1234",
"integer_value": 1234,
"level_one": {
"id": 1234,
"foo": "true",
"list_one": [],
"list_two": [
522
],
"url": "http://google.com",
"level_two": {
"thing_one": {
"yes": "false",
"no": "false"
},
"thing_two": {
"yes": "false",
"no": "false"
}
},
"another_field": "true",
"bar": 15000
}
}
递归字典函数:
def update_dictionary(template_dict, **kwargs):
for k, v in kwargs.items():
print(v)
print(isinstance(v, collections.Mapping))
if isinstance(v, collections.Mapping):
print("This is the k value")
print(k)
template_dict[k] = update_dictionary(template_dict.get(k, {}), v)
else:
print("We're going into the else now")
template_dict[k] = v
return template_dict
我从这里的另一个论坛获得了上述功能,但是在传递 kwargs 时它似乎不起作用。对于不在嵌套字典第一级中的任何字段,isinstance 检查结果为 False。任何帮助表示赞赏!
通过 kwargs 的测试行:
new_dict = update_dictionary(template_dict, another_field = 'false', integer_value=12345)
【问题讨论】:
-
键永远不会是
collections.Mapping的实例,至少在您实现可散列映射之前不会。你的意思可能是isinstance(v, collections.Mapping) -
啊,是的,这是我的错字。 (v, collections.Mapping) 在这种情况下也为所有嵌套的字典键返回 False。
-
另外,你需要继续传递
**kwargs....
标签: python python-3.x dictionary recursion