递归地替换字典中的字符 [英] Recursively replace characters in a dictionary

查看:99
本文介绍了递归地替换字典中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将所有点更改为下划线(在dict的键中),给定任意嵌套的字典

How do I change all dots . to underscores (in the dict's keys), given an arbitrarily nested dictionary?

我尝试的是写两个循环,但是我将被限制在2级嵌套字典。

What I tried is write two loops, but then I would be limited to 2-level-nested dictionaries.

{
    "brown.muffins": 5,
    "green.pear": 4,
    "delicious.apples": {
        "green.apples": 2
    {
}

...应该成为:

{
    "brown_muffins": 5,
    "green_pear": 4,
    "delicious_apples": {
        "green_apples": 2
    {
}

有优雅的方式吗?

推荐答案

您可以编写一个递归函数,像这样

You can write a recursive function, like this

from collections.abc import Mapping
def rec_key_replace(obj):
    if isinstance(obj, Mapping):
        return {key.replace('.', '_'): rec_key_replace(val) for key, val in obj.items()}
    return obj

当您使用您在问题中显示的字典来调用此字典时,您将获得一个新字典,其中的键被替换为 _ s

and when you invoke this with the dictionary you have shown in the question, you will get a new dictionary, with the dots in keys replaced with _s

{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}

说明

如果当前对象是 dict 的实例,如果是,则我们迭代字典,替换该键并递归调用该函数。如果它实际上不是一个字典,那么返回它。

Here, we just check if the current object is an instance of dict and if it is, then we iterate the dictionary, replace the key and call the function recursively. If it is actually not a dictionary, then return it as it is.

这篇关于递归地替换字典中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆