簡體   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