【问题标题】:Python3 - recursively replace all keys with periods in a nested dictionaryPython3 - 用嵌套字典中的句点递归替换所有键
【发布时间】:2023-07-20 16:33:01
【问题描述】:

我正在尝试在将嵌套字典插入 Mongo 之前对其进行清理。 dict 中的一些键中有句点,所以我需要用下划线替换它们。根据我看到的其他帖子,我想出了这个(不工作)代码示例:

def get_recursively(search_dict):
    new_dict = {}

    for key, value in search_dict.items():

        if '.' in key or ' ' in key:
            new_dict[key.replace('.', '_').replace(' ', '_').lower()] = value


        elif isinstance(value, dict):
            results = get_recursively(value)
            for key2, value2 in results.items():
                new_dict[key] = dict(key2, value2)

        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict):
                    more_results = get_recursively(item)
                    for key3, value3 in more_results.items():
                        new_dict[key] = dict(key3, value3)
        else:
            new_dict[key] = value

    return new_dict

我正在尝试制作一个新字典,因为当我尝试修改现有字典时,我收到一个关于字典在执行期间更改的错误。

无效的代码(至少)是: dict(key2, value2)

这不是有效的语法,但希望至少能展示我的思维过程。

非常感谢任何帮助。

【问题讨论】:

    标签: python-3.x dictionary recursion


    【解决方案1】:

    如果我没听错,这就是你的意思吗?

    def change_chars(string, chars, new_char):
        new_string = string
        for char in chars:
            new_string = new_string.replace(char, new_char)
        return new_string
    
    def recursively_change_keys(obj, chars, new_char):
        if isinstance(obj, list):
            return [
                recursively_change_keys(o, chars, new_char)
                for o in obj
            ]
    
        elif isinstance(obj, dict):
            return {
                change_chars(key, chars, new_char): recursively_change_keys(value, chars, new_char)
                for key, value in obj.items()
            }
    
        return obj
    

    所以你只需要像recursively_change(search_dict, [ ".", " " ], "_")这样称呼它

    【讨论】:

    • 谢谢。这适用于我的数据。你也是第一个回复的
    • 如果输入中的其他列表中直接存在列表(例如{'x.y': [[{'foo.1': 'bar'}], [{'foo.2': 'baz'}]]}),则此代码中的列表推导将无法正常工作。
    • @Blckknght 我不知道会发生这种情况,谢谢。我刚刚编辑了我之前的答案。
    【解决方案2】:

    试试:

    import json
    
    d = {
        "some.key": [
            {
                "key.1": {"a": 1},
                "key.2": 2,
                "key.3": {"key.4": [3, 4, 5], "key.5": 6},
            }
        ]
    }
    
    
    def transform(d):
        if isinstance(d, dict):
            return {k.replace(".", "_"): transform(v) for k, v in d.items()}
        elif isinstance(d, list):
            return [transform(v) for v in d]
        else:
            return d
    
    
    # pretty print the dictionary:
    print(json.dumps(transform(d), indent=4))
    

    打印:

    {
        "some_key": [
            {
                "key_1": {
                    "a": 1
                },
                "key_2": 2,
                "key_3": {
                    "key_4": [
                        3,
                        4,
                        5
                    ],
                    "key_5": 6
                }
            }
        ]
    }
    

    【讨论】:

      最近更新 更多