2017-04-05 167 views
0

如果我有一個函數必須爲字典內的嵌套字典執行。那我該如何執行它?Python字典遍歷特定操作/函數的嵌套字典

例如:

# I have the below dictionary 
d = {'a':1, 'b':2, 'c':3, 'd': {'e':4, 'f':5}} 

# I wanted a result as below 
{'a': 1, 'b': 2, 'c': 3, 'e': 4, 'f': 5} 

#I have executed it by 

for i, j in d.items(): 

    if type(j) == dict: 
     for key,value in d[i].items(): 
      d[key] = value 
     d.pop(i, None) 

print d 

#output 
{'a': 1, 'c': 3, 'b': 2, 'e': 4, 'f': 5} 

但是如果有很多的嵌套字典?我對此感到困惑?有什麼建議麼?

在此先感謝。

+0

遞歸調用? – bharadhwaj

+0

@bharadhwaj是 – Bhargav

回答

3

我認爲,這是扁平化的一種形式:

def flatten(d): 
    es = [d.pop(k) for k in sorted(d) if isinstance(d[k], dict)] 
    # Due to sorted the dictionaries those keys that are lexicographically after 
    # will overwrite the key-value pairs from those that are before. 

    # One would expect that `d.update(*es)` would work 
    # but it doesn't as `update` only takes one argument. 
    for e in es: 
     d.update(e) 

def flatten_many(d): 
    while any(isinstance(d[k], dict) for k in d): 
     flatten(d) 

第一個函數從彈出每d字典,然後用它們更新d。第二個函數應用flatten第一個函數,而有一個值是字典。

+0

謝謝..它讓我對嵌套字典的遞歸函數有所瞭解。我會練習更多。 :) – Bhargav

+0

Dan D.的答案沒有什麼是遞歸的(自我調用)。一切都是迭代的,因爲flatten()在flatten_many()的while循環中被調用。 –

+0

@ChristianKönig但我認爲pop函數在這裏遞歸執行。糾正我如果我錯了。 – Bhargav

2
dd={} 
def myprint(d): 
    for k, v in d.iteritems(): 
     if isinstance(v, dict): 
      myprint(v) 
     else: 
      dd.update({k:v}) 
    return dd 


d={'a':1, 'b':2, 'c':3, 'd': {'e':4, 'f':5,'g':{'h':6}}} 
print(myprint(d)) 

輸出 - { 'A':1, 'C':3, 'B':2, 'E':4, 'F':5, 'H':6}