2014-11-13 228 views
0

反向映射我有這個詞典嵌套字典

{ 
    'eth1': { 
      'R2': bw1, 
      'R3': bw3 
      }, 
    'eth2': { 
      'R2': bw2, 
      'R3': bw4 
     } 
} 

而且我想將它變成這個字典

{ 
    'R2': { 
     'eth1': bw1, 
     'eth2': bw2, 
    }, 
    'R3': { 
     'eth1': bw3, 
     'eth2': bw4 
    } 
} 

是否有這樣做的一個非常簡潔的方式?

+1

不,這是完全不可能的。 – Nearoo

回答

1

您可以使用嵌套循環要經過你的字典,並通過使用setdefault更新鍵/值構造新的。

d={ 
    'eth1': { 
      'R2': 'bw1', 
      'R3': 'bw3' 
      }, 
    'eth2': { 
      'R2': 'bw2', 
      'R3': 'bw4' 
     } 
} 
result = {} 
for k, v in d.iteritems(): 
    for a,b in v.iteritems(): 
     result.setdefault(a, {}).update({k:b}) 
print result 

輸出:

{'R2': {'eth2': 'bw2', 'eth1': 'bw1'}, 'R3': {'eth2': 'bw4', 'eth1': 'bw3'}} 

您可以使用列表解析嵌套循環寫小的解決方案,它會給出相同的結果。

result = {} 
res= [result.setdefault(a, {}).update({k:b}) for k, v in d.iteritems() for a,b in v.iteritems()] 
print result 

#Output: {'R2': {'eth2': 'bw2', 'eth1': 'bw1'}, 'R3': {'eth2': 'bw4', 'eth1': 'bw3'}} 
+0

這是一個非常整潔的解決方案。謝謝! – Jonathan

0

不知道爲什麼你會陷入低谷,這並不容易。像這樣的老套嵌套字典是PITA。這將工作:

d1 = { 
    'eth1': { 
      'R2': bw1, 
      'R3': bw3 
      }, 
    'eth2': { 
      'R2': bw2, 
      'R3': bw4 
     } 
} 

>>> d2 = {} 
>>> for k1, v1 in d1.items(): 
... for k2, v2 in v1.items(): 
...  if k2 not in d2: 
...  d2[k2] = {} 
...  d2[k2][k1] = v2 
... 
>>> d2 
{'R2': {'eth2': 'bw2', 'eth1': 'bw1'}, 'R3': {'eth2': 'bw4', 'eth1': 'bw3'}}