0

这里有很多类似的问题,但我找不到适合我的情况的问题,即使我可以调整一个类似的问题以适合我的情况,但到目前为止我还没有成功。

这是一个简单的问题:

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

我想将字典与常见的 ['operand']['id'] 合并

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

谢谢!

4

2 回答 2

1

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()
于 2013-10-29T16:22:09.820 回答
0

这是我的,也许有用...

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'}}]
于 2013-10-29T16:41:41.680 回答