Recursively replace characters in a dictionary

后端 未结 2 1276
难免孤独
难免孤独 2021-02-19 11:19

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

What I tried is write two loops, b

2条回答
  •  囚心锁ツ
    2021-02-19 11:48

    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
    

    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}
    

    Explanation

    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.

提交回复
热议问题