如何在python中将字典键拆分为多个单独的键?

2024-06-11 13:39:24 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我使用RRDTool Python包装器来存储和读取RRD数据库中的值。在

RRDTool for Python是RRDTool基于C的源代码/命令行实用程序的包装器。在

创建数据库后,我想使用python命令读取其标题:

header_info = rrdtool.info('database_file_name.rrd') 

相当于命令行实用程序:

^{pr2}$

哪个会打印标题信息:

filename = "database_file_name.rrd"
rrd_version = 5
...
ds[datasource_identifier_1].index = 0
ds[datasource_identifier_1].type = "GAUGE"
...
ds[datasource_identifier_2].index = 1
ds[datasource_identifier_2].type = "GAUGE"
...

在python中,命令行工具的输出用以下模式包装在一个大字典中:

key: value
"filename" : "database_file_name.rrd"
"ds[datasource_identifier_1].index" : "0"
"ds[datasource_identifier_2].type" : "GAUGE"

我现在正想办法把那本词典分开,这样我就可以这样查到它了:

index = dictionary["ds"]["datasource_identifier_1"]["index"]

但我不知道如何使用python实现这一点。我想这可以通过对原始字典进行迭代来完成,然后使用“[”、“]”和“.”作为触发器拆分这些键,然后创建一个新字典。在

我如何在Python中做到这一点呢?在


Tags: 命令行name实用程序数据库标题indextypeds
1条回答
网友
1楼 · 发布于 2024-06-11 13:39:24

我们需要解析这些键,看看它们是否看起来像ds[some_identifier].type等等

def process_dict(dictionary):
    import re    
    rgx = re.compile(r"^(ds)\[(.+?)\]\.(index|type)$")

    processed = {}

    for k, v in dictionary.items():
        # does k have the format ds[some_key].index etc
        m = rgx.search(k)
        if m:
            # create the embedded path
            ds, ident, attr = m.groups()
            processed.setdefault(ds, {}).setdefault(ident, {})[attr] = v
        else:
            processed[k] = v

    return processed

相关问题 更多 >