使用递归深层修改dict

class Test:
    def modify_dict(self, source, setting):
        """递归修改dict"""
        for key, val in setting.items():
            if isinstance(val, dict):
                self.modify_dict(source[key], val)
            else:
                source[key] = val
        return source

    def run(self):
        source = {"a": {"b": {"c": {"d": 1, "f": 3}}, "g": {"h": 1, "i": 2}}}
        setting = {"a": {"b": {"c": {"f": 777}}}}
        print(self.modify_dict(source, setting))


if __name__ == '__main__':
    test = Test()
    test.run()

# 运行结果:
{'a': {'b': {'c': {'d': 1, 'f': 777}}, 'g': {'h': 1, 'i': 2}}}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页