代码之家  ›  专栏  ›  技术社区  ›  David Gard

将python字符串(如'a.b.c=v')翻译到字典中

  •  -1
  • David Gard  · 技术社区  · 7 月前

    我有一个带有以下参数的参数解析器,它允许我指定 --configs 这将覆盖配置文件中可能指定的值。

    parser.add_argument('--configs', nargs='*', default=[])
    

    我的愿望是具体说明 --配置 格式为 k=v 例如-

    python my-app --configs foo=bar a.b.c=ddd
    

    然后在我的应用程序中,我希望将指定的值保存到字典中。使用上面的例子,字典应该输出如下-

    {'foo': 'bar', 'a': {'b': {'c': 'ddd'}}}
    

    然而,我正在努力将该值转换为字典结构,结果却得到了一个不正确的字典-

    {'foo': 'bar', 'a': {}, 'b': {}, 'c': 'ddd'}
    

    到目前为止,我有以下几点。我如何修改我的代码,以创建(或更新)正确的字典结构?

    import argparse
    import yaml
    
    
    parser = argparse. ArgumentParser()
    parser.add_argument('--config-file', help='Configuration file path.')
    parser.add_argument('--configs', nargs='*', default=[], help='Configuration settings.')
    args = parser.parse_args()
    
    
    if args.config_file:
        with open(args.config_file, 'r') as f:
            master_config = yaml.safe_load(f)
    else:
        master_config = {}
    
    
    for config in args.configs:
    
        # Split the setting into key and value.
        k, v = config.split('=', 1)
    
        # Split the key, if it's nested.
        ks = k.split('.')
    
        # Attempt to read the value as JSON.
        # This allows users to pass in either a simple string, or a JSON string.
        try:
            import json
            v = json.loads(v)
        except json.decoder.JSONDecodeError as e:
            pass
    
        # Set the master config value.
        # This is the section of code I am struggling with.
        l = len(ks)
        for i, x in enumerate(ks):
            if i != l-1:
                if not master_config.get(x):
                    master_config[x] = {}
            else:
                master_config[x] = v
    
    print(master_config)
    
    1 回复  |  直到 7 月前
        1
  •  1
  •   Michael Cao    7 月前

    反向工作以创建嵌套字典,然后更新您的 master_config

    k = 'a'
    v = 'ddd'
    
    ks = k.split('.')[::-1]
    
    master_config = {}
    
    if len(ks) == 1:
        master_config[k] = v
    else:
        nested_dict = {ks[0]: v}
        for x in ks[1:]:
            nested_dict = {x: nested_dict}
        
        master_config.update(nested_dict)