2016-04-26 135 views
2
def solution(dict, output, ini): 
    if (dict == None): 
     return None 
    else: 
     for key in dict: 
      if str(type(dict[key])) != str(type({})): 
       print(key) 
       output[ini + key] = dict[key] 
      else: 
       return solution(dict[key], output, ini + key + '.') 
    return output 

a = { 
    'Key1': '1', 
    'Key2': { 
     'a': '2', 
     'b': '3', 
     'c': { 
      'd': '3', 
      'e': '1' 
     } 
    } 
} 
print(solution(a, {}, "")) 

你好,我正在試圖做一個功能,展平嵌套字典。爲什麼此輸出每次都會返回不同的值?

例如一個應該打印:

{'Key2.b': '3', 'Key1': '1', 'Key2.c.d': '3', 'Key2.a': '2', 'Key2.c.e': '1'} 

但現在的代碼隨機給我回了正確的答案,但是從一系列的0-5如

{'Key2.b': '3', 'Key1': '1', 'Key2.c.d': '3', 'Key2.a': '2'}, 
{'Key2.b': '3', 'Key2.c.d': '3'} 

我發現如果我在我的其他語句中擺脫「返回」,它會起作用,但我不確定這是爲什麼?任何人都可以幫助我

回答

1

當您遍歷dict中的鍵for key in dict:時,它將以隨機順序返回鍵,因爲字典中的元素沒有排序。如果Key1首先被處理,它將被添加到輸出,並在下一次迭代Key2將被遞歸處理。現在,如果訂單不同,並且Key2首先被處理,那麼return solution(dict[key],output,ini+key+'.')將導致在Key1被添加到輸出之前返回結果。 Key2中的嵌套元素也一樣。如果您刪除return語句,則無論迭代順序如何,所有鍵都將被處理,您將得到預期的輸出。

0

爲你把結果output,你不應該在returnelse,否則,for循環將打破,其餘的按鍵將被忽略。(只是刪除return,它會做的工作)

相關問題