2012-09-25 119 views
1

關於此主題有許多問題,但我還未能適應解決方案以適應我的情況。本來我的字典,我從一個平面文件得到的列表:將詞典列表轉換爲嵌套詞典

[{'Name': 'Jim', 'Attribute': 'Height', 'Value': '6.3'}, 
{'Name': 'Jim', 'Attribute': 'Weight', 'Value': '170'}, 
{'Name': 'Mary', 'Attribute': 'Height', 'Value': '5.5'}, 
{'Name': 'Mary', 'Attribute': 'Weight', 'Value': '140'}] 

,我想將其轉換爲一個嵌套的字典,該屬性/值對與每一個名字:

{ 
    'Jim': {'Height': '6.3', 'Weight': '170'}, 
    'Mary': {'Height': '5.5', 'Weight': '140'} 
} 
+1

我不認爲你可以在一個字典中有兩個帶有不同值的'Jim'鍵。 – Kevin

+1

那麼http://www.whathaveyoutried.com? –

+0

@Kevin - 謝謝糾正排字錯誤 –

回答

7

使用defaultdict便於處理這些條目:

output = defaultdict(dict) 

for person in people: 
    output[person['Name']][person['Attribute']] = person['Value'] 
+0

很好的答案...我沒有仔細閱讀第一遍的問題。 –

2

檢查我NestedDict類在這裏:https://stackoverflow.com/a/16296144/2334951

>>> d = [{'name': 'Jim', 'attribute': 'Height', 'value': 6.3}, 
...  {'name': 'Jim', 'attribute': 'Weight', 'value': 170}, 
...  {'name': 'Mary', 'attribute': 'Height', 'value': 5.5}, 
...  {'name': 'Mary', 'attribute': 'Weight', 'value': 140}, ] 
>>> result = NestedDict() 
>>> for i in d: 
...  path = [i['name'], i['attribute']] # list of keys in order of nesting 
...  result[path] = i['value'] 
>>> print(result) 
{'Mary': {'Height': 5.5, 'Weight': 140}, 'Jim': {'Height': 6.3, 'Weight': 170}}