input = { "a" : { "x": 1, "y": 2 },
"b" : { "x": 3, "z": 4 } }
output = {'y': {'a': 2},
'x': {'a': 1, 'b': 3},
'z': {'b': 4} }
我需要爲輸入創建一個新的字典,並將其作爲輸出。到目前爲止我已經寫:如何在不覆蓋舊值的情況下更新字典中的密鑰
def pivot_nested_dict(nested_dict):
5 stateDict={}
6 for i in nested_dict:
7 dict2=nested_dict[i]
8 for j in dict2:
9 stateDict[j]= {i: dict2[j]}
10 return stateDict
11
12 print pivot_nested_dict(input)
我幾乎有答案,輸出= { 'Y':{ '一個':2}, 'X':{ 'B':3}, 'Z': {'b':4}}。 因此,x鍵將覆蓋'a':1.如何保留a和b?
它不清楚你想要什麼。我看到你正在提供一個輸入 - >輸出對,但它仍然不能破譯你想要的。尤其是因爲從我坐的地方來看,這幾乎是隨意的排列。 – adityajones
輸出只是爲了顯示我的輸出應該是什麼 – user2943615
如果這樣簡單,用'return {'y':{'a':2},'x'替換你的代碼體:{'a' :1,'b':3},'z':{'b':4}}' – Steve314