2012-09-25 121 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}}