2017-04-05 9 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を更新します。第2の関数は、辞書である値がある間に第1の関数flattenを適用する。

+0

ありがとう..それは私にネストされた辞書への再帰関数の洞察を与えました。私はもっ​​と練習します。 :) – Bhargav

+0

Dan D.の答えには再帰的(自己呼び出し)はありません。 flatten_many()からwh​​ileループでflatten()が呼び出されるため、すべてが繰り返し実行されます。 –

+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)) 

出力 - { '':1、 'C':3、 'B':2、 'E':4 'F':5 'H':6}

関連する問題