简体   繁体   English

如何在基于字符串值的复杂树状嵌套dict中搜索键值对,该字符串值在Python中包含类似于Jinja的分隔符

[英]How to search for key value pairs in a complex tree-like nested dict based on string values which contains a Jinja-like separators in Python

I have a dictionary which contains nested dictionaries and nested lists of dictionaries. 我有一本字典,其中包含嵌套的字典和嵌套的字典列表。 It goes few levels deeper then that. 然后再往下走几层。 Some random keys will have values which will contain double hashes as a delimiters (same like Jinja's double curly braces). 一些随机键的值将包含双哈希作为定界符(类似于Jinja的双花括号)。 Those will be the entire string value of some random key. 这些将是某个随机键的整个字符串值。 I need to figure out what is the key name for where I've found a value which contains the double hashes and what is the value in between. 我需要找出在哪里找到一个包含双哈希值的值以及这两个值之间的值的键名是什么。

I tried to think about a solution of translating the json into a string and simply look for the double hashes, like in 'sed' plus some string parsing, but I might loose the tractability for the key name, and this might get ugly. 我试图考虑一种将json转换为字符串并仅查找双重哈希的解决方案,例如在'sed'中加上一些字符串解析,但是我可能会失去键名的易处理性,这可能会变得很丑陋。 Trying to recourse over the master dict object did not help either because the data structure is complex, sometimes inside a dict there's a list and so on. 尝试求助于主dict对象无济于事,因为数据结构很复杂,有时在dict中有一个列表,依此类推。

Example Dict: 示例示例:

{
    "key": 7,
    "networksCollection": [
        {
            "key": 47,
            "subnet": {
                "key": 73,
                "prefixDelegationEnabled": "##prefix##"
            },
            "providerSegmentationID": null,
            "providerPhysicalNetwork": "##physicalNetwork##"
        }

         ]
}

A flat dictionary as an output could be nice. 平面字典作为输出可能会很好。 something like: 就像是:

{ "prefixDelegationEnabled": "prefix", "providerPhysicalNetwork": "physicalNetwork"}

Using this flat dict, and based on those keys it will contain, I will build an html form where the user will be prompted to populate values for those keys, where I will need to replace the double hashes place-holders with those values - meaning I will need a way to trace back to populate those place-holders 使用这款平板快译通,以及基于这些按键它将包含,我将建立一个HTML表单,用户将被提示填入值的钥匙,在那里我将需要使用这些值来代替双哈希占位 - 意义我将需要一种方法来回溯以填充这些占位符

You can use a generator for that purpose which traverses the nested structure and yields key-value pairs for which the criterion is met: 为此,您可以使用生成器,该生成器遍历嵌套结构并生成满足条件的键值对:

def find_key_value_pairs(obj):
    if isinstance(obj, list):
        for item in obj:
            yield from find_key_value_pairs(item)
    elif isinstance(obj, dict):
        for key, value in obj.items():
            if isinstance(value, str) and value.startswith('##') and value.endswith('##'):
                yield key, value.strip('#')
            elif isinstance(value, (dict, list)):
                yield from find_key_value_pairs(value)

Then you can obtain the result via: 然后,您可以通过以下方式获得结果:

result = dict(find_key_value_pairs(test))

where test is your example dict. test是您的示例字典。

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

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