2017-09-13 19 views
-2

キーの値を入れ子になった私はこのような辞書があります。Pythonの辞書の変更は

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

をし、私は新しいUUIDを持つすべての_id年代を変更したいです。これをPythonで実現する方法はありますか?

ありがとうございました。

+0

新しいIDはすべての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を表し、辞書を提供する必要がありますパラメータ。あなたが選択した道

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) 

はあなた次第です。そうでなければ、あなたもこのような新しい_idを生成するために、すべてのノードのために呼び出される関数を有する第二の辞書を置き換えることができます。

最後に、あなたがこのように最初のバージョンを呼び出すことができます。

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

updateData(data, idUpdate) 

と、このような第二1:ここでは

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