2017-05-17 43 views
-1

映射由列表和字典組成的兩個數據結構。 data的映射應遞歸應用於​​結構。在嵌套數據結構中映射字符串

這是我投入

data = { 
    'a': 'Apple', 
    'b': 'Ball', 
    'c': 'Cat', 
    'd': 'Dog', 
    'e': 'Egg', 
    'f': 'Fish', 
    'g': 'Goat', 
    'h': 'House', 
    'i': 'Ice-Cream', 
    'j': 'Jaguar', 
    'k': 'Key', 
    'l': 'Lock', 
    'm': 'Map' 
} 

payload = { 
    'PI': [ 
     { 
      'one': 'a', 
      'two': 'b', 
      'three': 'c', 
      'four': { 
       'five': 'd', 
       'six': 'e', 
       'seven': 'f', 
       'eight': 'g' 
      } 
     }, { 
      'nine': 'h', 
      'ten': 'i', 
      'eleven': 'j', 
      'twelve': 'k' 
     } 
    ] 
} 

預期輸出:

payload = { 
    'PI': [ 
     { 
      'one': 'Apple', 
      'two': 'Ball', 
      'three': 'Cat', 
      'four': { 
       'five': 'Dog', 
       'six': 'Egg', 
       'seven': 'Fish', 
       'eight': 'Goat' 
      } 
     }, { 
      'nine': 'House', 
      'ten': 'Ice-Cream', 
      'eleven': 'Jaguar', 
      'twelve': 'Key' 
     } 
    ] 
} 

這是我的,但在嘗試創建映射它不工作

def mapping(payload): 
    for k,v in payload.items(): 
     if(isinstance(v,dict)): 
      mapping(v) 
     elif(isinstance(v,list)): 
      for item in v: 
       mapping(item) 
     else: 
      try: 
       v = data[v] 
      except KeyError: 
       pass 
     return payload 

我得到這個代替:

{ 
    'PI': [ 
     { 
      'four': { 
       'eight': 'g', 
       'five': 'd', 
       'seven': 'f', 
       'six': 'e' 
      }, 
      'one': 'a', 
      'three': 'c', 
      'two': 'b' 
     }, 
     { 
      'eleven': 'j', 
      'nine': 'h', 
      'ten': 'i', 
      'twelve': 'k' 
     } 
    ] 
} 

什麼也沒有更換。

回答

0

你確實可以使用遞歸;遞歸列表值和字典元素,並且直接映射其他所有內容。不要忘記返回的結果;遞歸函數創建新的字典和列表:

def replace_strings(value, mapping): 
    if isinstance(value, list): 
     return [replace_strings(v, mapping) for v in value] 
    if isinstance(value, dict): 
     return {replace_strings(k, mapping): replace_strings(v, mapping) 
       for k, v in value.items()} 
    return mapping.get(value, value) 

演示:

>>> pprint(replace_strings(payload, data)) 
{'PI': [{'four': {'eight': 'Goat', 
        'five': 'Dog', 
        'seven': 'Fish', 
        'six': 'Egg'}, 
     'one': 'Apple', 
     'three': 'Cat', 
     'two': 'Ball'}, 
     {'eleven': 'Jaguar', 
     'nine': 'House', 
     'ten': 'Ice-Cream', 
     'twelve': 'Key'}]} 

你的代碼有幾個問題:

  • 你忽略任何遞歸調用的返回值。
  • 您返回了原始輸入,保持不變。