Ezer K Ezer K - 7 days ago 5
Python Question

list of python (nested) dicts to one nested dict

I have a list of dicts that looks something like this:

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


I want to convert it into one deep nested dict:

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


seen a couple of solutions around, but all seem to assume a constant deepness of the product and I'm looking for something general

Thanks

Answer

Try this:

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[key] = temp
print new

Which should yield

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

Now if there are multiple rights, wrongs or no_predictions in the original data you need some logic to handle that. Maybe with a list? May I ask where you intend to use this code?