开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜