python - 如何从其键是引用字典子集的嵌套字典创建平面字典?

标签 python dictionary recursion generator indirection

我正在创建一个嵌套引用字典来记录数据字典可能具有的所有可能的键以及相应的值,这些值是平面字典中要使用的所有键。

数据字典的键始终是引用字典的键的子集。平面字典的键始终是引用字典值集的子集。

换句话说,给定一个带有如下分配的引用字典:

reference['agent']['address'] = 'agentaddress'
reference['agent']['zone']['id'] = 'agentzoneid'
reference['eventid'] = 'eventid'
reference['file']['hash'] = 'filehash'
reference['file']['name'] = 'filename'

和一个带有如下分配的数据字典:

nested['agent']['address'] = '172.16.16.16'
nested['eventid'] = '1234566778'
nested['file']['name'] = 'reallybadfile.exe'

代码应该生成一个字典,可以像这样分配:

flat['agentaddress'] = '172.16.16.16'
flat['eventid'] = '1234566778'
flat['filename'] = 'reallybadfile.exe'

我永远无法知道嵌套字典中的哪些字段将被填充,哪些不会,但我可以知道引用字典中的映射。

我希望我需要使用递归将字典遍历到子字典中,并且可能需要某种间接方式来分别从引用字典值和嵌套字典键创建平面字典键和值。

但是,我还无法生成有意义的代码。

也许从非常高的层面来看,它可能看起来像这样:

def this(ref, nest, flat, *args):
    for (k,v) in reference:
        if type(v) is dict:
            this(?, ?, ?, ?)
        elif nested[path][to][k]:      
            flat[reference[path][to][k]] = nested[path][to][k]

其中 [path][to][k] 表示进行间接寻址的某种方式,而 *args 是我传递给递归函数的内容,以便我将有一种方法拥有足够的上下文来通过字典的嵌套来引用我需要的键和值。

最佳答案

使用 generator ,这相当简单:

代码:

def make_flat_tuples(data, ref):
    for k, v in data.items():
        if isinstance(v, dict):
            for x in make_flat_tuples(v, ref[k]):
                yield x
        else:
            yield ref[k], v

flat = dict(make_flat_tuples(nested, reference))

测试代码:

from collections import defaultdict

reference = defaultdict(dict)
reference['agent'] = defaultdict(dict)

reference['agent']['address'] = 'agentaddress'
reference['agent']['zone']['id'] = 'agentzoneid'
reference['eventid'] = 'eventid'
reference['file']['hash'] = 'filehash'
reference['file']['name'] = 'filename'

nested = defaultdict(dict)

nested['agent']['address'] = '172.16.16.16'
nested['eventid'] = '1234566778'
nested['file']['name'] = 'reallybadfile.exe'

print(dict(make_flat_tuples(nested, reference)))

结果:

{
    'agentaddress': '172.16.16.16', 
    'eventid': '1234566778', 
    'filename': 'reallybadfile.exe'
}

关于python - 如何从其键是引用字典子集的嵌套字典创建平面字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030287/

相关文章:

python - 使用 OpenCV 进行图像检测

python - python SyntaxError : unexpected EOF while parsing

python - 在 PowerShell 中设置 Python 的路径?

javascript - 从获取字符串数组到获取键值对数组

Java对象不能通过递归通过ref传递

c - 找到将 N 减少到零的最小步数

python ujson。错误 : Could not build wheels for ujson which use PEP 517 and cannot be installed directly

python - 以元组为键的字典

c++ - 检查map<string, string>是否包含另一个map<string, string>

c - 需要解释 "Towers of Hanoi"中的递归调用