【问题标题】:list of python (nested) dicts to one nested dict一个嵌套字典的python(嵌套)字典列表
【发布时间】:2016-11-29 09:31:10
【问题描述】:

我有一个看起来像这样的字典列表:

[{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'}}

看到了一些解决方案,但似乎都假设产品的深度不变,我正在寻找一般性的东西

谢谢

【问题讨论】:

  • 您应该展示您尝试过的内容以及遇到的问题。 SO 不是代码编写服务。

标签: python dictionary nested


【解决方案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,您需要一些逻辑来处理它。也许有一个清单?请问您打算在哪里使用此代码?

【讨论】:

    【解决方案2】:

    为什么你不尝试使用字典树? 您可以将字典放在“数据”中。

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

    看这里(页尾):treeLib

    【讨论】:

    • 欢迎来到 Stack Overflow!虽然这在理论上可以回答问题,it would be preferable 在此处包含答案的基本部分,并提供链接以供参考。
    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多