繁体   English   中英

configparser 中的多维字典

[英]Multi-dimension dictionary in configparser

是否可以使用 Python 'configparser' 使用缩进来存储多维字典(3 深)? 解决方法是拆分键值,但想知道是否有一种干净的方法可以直接导入字典。

不起作用 - 在 CONFIGPARSER 中使用子选项缩进

[OPTIONS]
        [SUB-OPTION]
        option1 = value1
        option2 = value2
        option3 = value3

作品 - 用于子选项值的拆分

[OPTIONS]
    SUB-OPTION  = 'option1, value1',    
                  'option2, value2',
                  'option3, value3'

字典值

dict['OPTIONS']['SUB-OPTION'] = {
        option1 : value1,
        option2 : value2,
        option3 : value3,
    }

config.ini文件

OPTIONS  = {"option1": "value1", "option2": "value2", "option3": "value3"}

码:

import json
options = json.loads(conf['OPTIONS'])

ASAIK,那里 (见下文)该格式的嵌套配置文件。

我建议像配置文件json:

{
 "OPTIONS": {
   "SUB-OPTIONS": {
     "option1" : value1,
     "option2" : value2,
     "option3" : value3,
   }
 }
}

然后在代码中使用:

from ast import literal_eval
with open("filename","r") as f:
 config = literal_eval(f.read())

编辑

或者,您可以使用YAML(使用PyYAML)作为一个很棒的配置文件。

以下配置文件:

option1:
    suboption1:
        value1: hello
        value2: world
    suboption2:
        value1: foo
        value2: bar

可以使用以下方法解析:

import yaml
with open(filepath, 'r') as f:
    conf = yaml.safe_load(f)

然后你可以像在dict那样访问数据:

conf['option1']['suboption1']['value1']
>> 'hello'

正如其他人指出的那样:当前的configparser实现不支持请求的嵌套功能。

但是, TOML配置文件遵循与INI文件类似的语法并允许嵌套结构。 请参阅正式规范在这里和相应的Python库在这里

您还可以使用以下示例在 SO 上查看此问题

name = "A Test of the TOML Parser"

[[things]]
a = "thing1"
b = "fdsa"
multiLine = """
Some sample text."""

[[things]]
a = "Something else"
b = "zxcv"
multiLine = """
Multiline string"""
[[things.objs]]
x = 1
[[things.objs]]
x = 4
[[things.objs]]
x = 7
[[things.objs.morethings]]
y = [
    2,
    3,
    4
]
[[things.objs.morethings]]
y = 9

[[things]]
a = "3"
b = "asdf"
multiLine = """
thing 3.
another line"""

JSON输出:

{
    "name": "A Test of the TOML Parser",
    "things": [{
        "a": "thing1",
        "b": "fdsa",
        "multiLine": "Some sample text."
    }, {
        "a": "Something else",
        "b": "zxcv",
        "multiLine": "Multiline string",
        "objs": [{
            "x": 1
        }, {
            "x": 4
        }, {
            "x": 7,
            "morethings": [{
                "y": [2, 3, 4]
            }, {
                "y": 9
            }]
        }]
    }, {
        "a": "3",
        "b": "asdf",
        "multiLine": "thing 3.\\nanother line"
    }]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM