开发者

Python: Elegant way to replace a given dictionary by child key somewhere in a tree?

开发者 https://www.devze.com 2023-01-04 01:45 出处:网络
Is the开发者_如何学Pythonre some kind of enumeration library or method I should use or should I write from scratch with recursion?

Is the开发者_如何学Pythonre some kind of enumeration library or method I should use or should I write from scratch with recursion?

I'm parsing a JSON tree into an object tree as it happens, and I'd like to replace some nodes with other kinds of objects.

E.g:

db = {'bigBang' :
          {'stars':
               {'planets': {}, 'is_list':true
               }
           }
     }
db.deepReplace( 'is_list', ['earth', 'mars'] )
>> db is now: 
>> {'bigBang' :
>>        {'stars':
>>             {'planets':
>>                 {
>>                     ['earth', 'mars']
>>                 }
>>             }
>>         }
>> }


If you know there's only one node to replace:

def deepReplace(d, key, value):
    if isinstance(d, dict):
        if key in d:
            d[key] = value
            return True
        else:
            for k,v in d.iteritems():
                if deepReplace(v, key, value):
                    return True
    return False

Otherwise:

def deepReplace(d, key, value):
    if isinstance(d, dict):
        if key in d:
            d[key] = value
        else:
            for k,v in d.iteritems():
                deepReplace(v, key, value):


It's hard to tell exactly what you're trying to accomplish; I guess you want deepReplace to replace any node named "planets" with a map containing "earth" and "mars"?

It's pretty easy to write that function, especially if you know the tree will contain dicts. If not, you need to test the type (or catch the errors) when you try and recurse.

def deep_replace(d, key, replacement):
    for k, value in d.items():
        if k == key:
            d[k] = replacement
        else:
            deep_replace(value, key, replacement)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号