2014-07-23 31 views
1

我在將字典轉換爲具有遞歸功能的字符串時遇到了問題。 我有一個如下路由的地圖;python遞歸字典轉換爲字符串

urls = { 
    '/' : 'BaseController.hello', 
    '/api' : { 
     '/auth' : { 
      '/me' : 'ApiController.hello', 
      '/login' : { 
       '/guest' : 'ApiController.guest_login', 
       '/member': 'ApiController.member_login' 
      } 
     } 
    } 
} 

我需要做的是從中生成一個字典到以下;

url_map = { 
    '/' : 'BaseController.hello', 
    '/api/auth/me' : 'ApiController.hello', 
    '/api/auth/login/guest' : 'ApiController.guest_login', 
    '/api/auth/login/member': 'ApiController.member_login', 
} 

此功能被稱爲路由分組,但我一直沒有能夠編寫一個函數來生成該功能。有任何想法嗎 ?

+0

*我一直沒能寫一個函數*, - 顯示您的嘗試呢。 – vaultah

回答

3

您可以遞歸不喜歡這樣

def flatten(current_dict, current_key, result_dict): 

    # For every key in the dictionary 
    for key in current_dict: 
     # If the value is of type `dict`, then recurse with the value 
     if isinstance(current_dict[key], dict): 
      flatten(current_dict[key], current_key + key, result_dict) 
     # Otherwise, add the element to the result 
     else: 
      result_dict[current_key + key] = current_dict[key] 
    return result_dict 

print flatten(urls, "", {}) 

輸出

{ 
    '/api/auth/me': 'ApiController.hello', 
    '/api/auth/login/guest': 'ApiController.guest_login', 
    '/': 'BaseController.hello', 
    '/api/auth/login/member': 'ApiController.member_login' 
} 
+0

謝謝,它的工作:) – aacanakin

+0

我會想,你將不得不在遞歸調用中通過'''result_dict'' - 這是否工作,因爲'dict'是一個可變的默認參數? – wwii

+0

@wwii它的工作原理是,只有在函數被定義時纔會評估默認參數,而不是在調用時才評估。 – thefourtheye