2017-09-13 141 views
-2

我的字典是这样的:蟒蛇字典改变嵌套键值

{ 
    '_id': 'uuid1', 
    'languages':{'_id':'uuid2'}, 
    'experiences':{'_id':'uuid3', 
        'values': [{'_id':'uuid4'}, 
           'responsibilities':{'_id':'uuid5', 
                'values':[{'_id':'uuid6'}]} 
          ] 
        } 
} 

,我想改变这一切_id与新的UUID。有没有办法在Python中实现这一点?

谢谢。

+0

新的uuid对每个id都是一样的吗? –

+0

是的,访问每个元素寻找'_id'键,然后更新... –

+0

不,我会生成新的uuids。我如何遍历所有嵌套字典和数组? – bluewa

回答

0

下面是Python: Recommended way to walk complex dictionary structures imported from JSON?

s = { 
    '_id': 'uuid1', 
    'languages': { '_id':'uuid2' }, 
    'experiences': { 
     '_id':'uuid3', 
     'values': [ { '_id':'uuid4' } ], 
     'responsibilities': { 
      '_id':'uuid5', 
      'values': [ { '_id':'uuid6' } ] 
     } 
    } 
} 

def walk(node): 
    if type(node) == type([]): 
     for item in node: 
      walk(item) 
    elif type(node) == type({}): 
     for key, item in node.items(): 
      if type(item) in (type([]),type({})): 
       walk(item) 
      else: 
       if key == '_id': 
        node[key] = 'xxx' # whatever you like 

walk(s) 

from pprint import pprint 
pprint(s) 

启发脚本输出

{'_id': 'xxx', 
'experiences': {'_id': 'xxx', 
       'responsibilities': {'_id': 'xxx', 
             'values': [{'_id': 'xxx'}]}, 
       'values': [{'_id': 'xxx'}]}, 
'languages': {'_id': 'xxx'}} 
0

您可以递归地解决这个问题是这样的:

def updateData(data, newIDs): 
    for key in data: 
     if key == "_id": 
      if data[key] in newIDs: 
       data[key] = newIDs[data[key]] 
     if isinstance(data[key], dict): 
      updateData(data[key], newIDs) 

你必须提供具有改变作为第一个参数的字典,它代表了_id S的应该改变为第二字典参数。否则,你也可以更换第二字典,一个将被称为为每个节点生成新_id这样的功能:

def updateData(data, idGenerator): 
    for key in data: 
     if key == "_id": 
      if data[key] in newIDs: 
       data[key] = idGenerator(data[key]) 
     if isinstance(data[key], dict): 
      updateData(data[key], newIDs) 

你选择哪种方式取决于你。

最后,你可以调用这个方法的第一个版本:

idUpdate = {"uuid1":"ooid1", "uuid2":"ooid2", "uuid3":"ooid3", 
      "uuid4":"ooid4", "uuid5":"ooid5", "uuid6":"ooid6"} 

updateData(data, idUpdate) 

,第二个是这样的:

def newIdGenerator(oldID): 
    return the_new_id 
updateData(data, newIdGenerator)