一个嵌套字典的python(嵌套)字典列表

时间:2016-11-29 09:31:10

标签: python dictionary nested

我有一个类似于以下内容的词典列表:

[{u'control_set': {u'no_prediction': 'v1'}}
{u'control_set': {u'wrong': 'v2'}}
{u'prediction_set': {u'right': 'v4'}}
{u'prediction_set': {u'wrong': 'v3'}}]

我想将它转换为一个深层嵌套的字典:

{u'control_set' : {u'no_prediction': 'v1',u'wrong': 'v2'}
 u'prediction_set' : {u'wrong' : 'v3', u'right' : 'v4'}}
看到了几个解决方案,但所有人似乎都假设产品一直保持深度,我正在寻找一般性的东西

由于

2 个答案:

答案 0 :(得分:1)

为什么你不尝试使用词典之树? 您可以将字典放在"数据"。

tree = Tree()
tree.create_node("x", "x")  # root node
tree.create_node("y", "Y", parent="x",data=dict)

点击此处(页面末尾):treeLib

答案 1 :(得分:1)

试试这个:

orig = [{u'control_set': {u'no_prediction': 'v1'}},
        {u'control_set': {u'wrong': 'v2'}},
        {u'prediction_set': {u'right': 'v4'}},
        {u'prediction_set': {u'wrong': 'v3'}}]

new = {}
for row in orig:
    for set_name, inner in row.items():
        temp = new.get(set_name, {})
        temp.update(inner)
        new[set_name] = temp
print new

哪个应该产生

{'prediction_set': {'wrong': 'v3', 'right': 'v4'},
 'control_set': {'no_prediction': 'v1', 'wrong': 'v2'}}

现在,如果原始数据中存在多个权限,错误或no_predictions,则需要一些逻辑来处理它。也许有一个清单?请问您打算在何处使用此代码?

相关问题