Francesco Della Vedova
Francesco Della Vedova

Reputation: 943

Merge list of dictionaries by nested key

there's plenty of similar questions here, but I couldn't find one that works for my case, and even if I could probably tweak one similar problem to work for my case, I haven't had success so far.

Here's the simple issue:

my = [
    {'operator': 'SET', 'operand': {'id': '9999', 'name': u'Foo'}}, 
    {'operator': 'SET', 'operand': {'status': 'ACTIVE', 'id': '9999'}}]

I want to merge the dictionaries with common ['operand']['id']

result = [
    {'operator': 'SET', 'operand': {'id': '9999', 'name': u'Foo', 'status': 'ACTIVE'}}]

Thanks!

Upvotes: 0

Views: 79

Answers (2)

Christian Tapia
Christian Tapia

Reputation: 34146

Heres is mine, maybe is useful...

my = [ {'operator': 'SET',
    'operand': {'id': '9999', 'name': u'Foo'} }, 
   {'operator': 'SET',
    'operand': {'status': 'ACTIVE', 'id': '9999'} }   ]

def merge(mylist):
    res_list = [{}]
    tmp_dict = {}
    for mydict in mylist:        
        for k in mydict.keys():
            if type(mydict[k]) == dict:
                for k2 in mydict[k]:
                    if k2 not in tmp_dict.keys():
                        tmp_dict[k2] = mydict[k][k2]
                res_list[0][k] = tmp_dict                            
            else:
                res_list[0][k] = mydict[k]

    return res_list

print f(my)
>>> 
[{'operator': 'SET', 'operand': {'status': 'ACTIVE', 'id': '9999', 'name': u'Foo'}}]

Upvotes: 0

Wolph
Wolph

Reputation: 80031

It seems a fairly easy problem, with a bit of experimentation you should be able to do it :)

Here's my version but there are many ways of solving the problem:

def merge(x):
    out = {}
    for y in x:
        id_ = y['operand']['id']
        if id_ not in out:
            out[id_] = y
        else:
            out[id_]['operand'].update(y['operand'])

    return out.values()

Upvotes: 1

Related Questions