python - 从破折号分隔的字符串创建多级字典(未知多深)

标签 python python-3.x

对于“健康检查”项目,我尝试从文本文件中写入的字符串创建一个多维数组。

目前我可以使用这样的单个变量:

someParameter1 = someValue1 # With some comments
someParameter2 = someValue2 # With some other comments

这将被翻译成字典:

ini['someParameter1'] = 'someValue1'
ini['someParameter2'] = 'someValue2'

现在我刚刚添加了对表的检查,因此我使用二维数组,从破折号分隔的字符串构建,如下所示:

someTable-someParameter1 = someValue1 # With some comments
someTable-someParameter2 = someValue2 # With some other comments

这将被翻译成两层字典:

ini['someTable']['someParameter1'] = 'someValue1'
ini['someTable']['someParameter2'] = 'someValue2'

为此,我在“=”符号之前硬编码了 2 个字段的限制:

# In case the key contains a dash, create a 2-dimensional key
for inikey in list(ini):  # loop thru the ini to find key's with a dash
    if '-' in inikey:
        part1,part2 = inikey.split('-',1)    # <= Only split on the first dash
        try:
            ini[part1][part2] = ini[inikey]
        except KeyError:  # In case ini[part1] does not exist yet
            ini[part1] = {}
            ini[part1][part2] = ini[inikey]

因此,当我的配置文件中有:aaa-bbb-ccc-ddd = xyz时,这将被转换为ini['aaa']['bbb- ccc-ddd'] = 'xyz'

现在我正在寻找一个技巧来创建ini['aaa']['bbb]['ccc']['ddd'] = 'xyz'无需为每个预期数量的级别编写一段代码。 因此,如果可能的话,在 = 之前也可以使用 3、4 或任意数量的单词,创建一个维度未知的列表,深度根据需要而定。

最佳答案

您可以使用defaultdict并使用默认字典创建它。如果你称其为,我们就有了一个递归数据结构:

from collections import defaultdict

def Tree():
    return defaultdict(Tree)

每次使用新 key 时,这都会创建新的子树:

>>> tree = Tree()
>>> tree['a']['b']['c'] = 123

如果我们有一个键列表,我们可以循环遍历它们并跟踪每个子树,直到我们使用除最后一个键之外的所有键。然后我们设置最后一个子树中最后一个键的值:

ini = Tree()

config_line = 'aaa-bbb-ccc-ddd = xyz'
keys, value = config_line.split(' = ')

keys = keys.split('-')

subtree = ini
for key in keys[:-1]:
    subtree = subtree[key]

subtree[keys[-1]] = value

关于python - 从破折号分隔的字符串创建多级字典(未知多深),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59571190/

相关文章:

python - 从Pool.async_map返回第一个非零结果

python - 在python 3.6中从公钥到公共(public)地址生成比特币 key 对

python - 子列表的唯一元素取决于子列表中的特定值

python - 如何迭代枚举 Flag 子类中的 *distinct* 标志?

python - 带有自签名证书的 Authlib SSLError

python - Alembic 迁移以将串行字段转换为整数

在 Electron 应用程序中作为子进程运行时,Python 找不到已安装的模块

python - PostgreSQL 多用户应用程序

python - 如何在scrapy中获取div中<p>标签的数量?

python - 'read_csv'数据的内存与原始数据不同