如何将'key=value'字符串转为嵌套字典并修正Python代码问题
修正嵌套Key的字典赋值问题
原代码在处理a.b.c=ddd这类嵌套键值对时,错误地将每个层级的键都作为顶层键添加到master_config中,导致生成扁平字典。以下是修正后的代码,重点修改注释Set the master config value for the current setting下方的逻辑:
### For context - in reality I use an argument parser with two args. ### --config-file - Path to a YAML configuration file. If present, ### this file will be read into Python as a dictionary called ### `master_config`. If not, an empty dictionary of the same name ### will be created. ### --configs - Single 'key=value' settings that will be read into ### `master_config` and either override settings defined in the ### YAML configuration file, or set a value. master_config = {'foo': 'baz'} configs = ['foo=bar', 'a.b.c=ddd'] for config in configs: # Split the setting into key and value. k, v = config.split('=', 1) # Split the key, if it's nested. ks = k.split('.') # Set the master config value for the current setting. current_dict = master_config # 遍历除最后一个键以外的所有层级 for key in ks[:-1]: # 如果键不存在,或者对应的值不是字典,则创建空字典 if key not in current_dict or not isinstance(current_dict[key], dict): current_dict[key] = {} # 进入下一层字典 current_dict = current_dict[key] # 设置最后一个键的值 current_dict[ks[-1]] = v print(master_config)
修正逻辑说明
- 用
current_dict变量跟踪当前操作的字典层级,初始指向master_config - 遍历嵌套键的前N-1个层级:
- 检查当前层级的键是否存在,且对应的值是字典;如果不满足则创建空字典
- 将
current_dict切换为当前键对应的子字典,逐步深入嵌套结构
- 最后在最内层的字典中设置最后一个键的值,确保嵌套结构正确生成
运行修正后的代码,输出结果为:
{'foo': 'bar', 'a': {'b': {'c': 'ddd'}}}
完全符合预期的嵌套字典结构。
内容的提问来源于stack exchange,提问作者David Gard
相关产品推荐
相关产品推荐

