2013-10-29 68 views
0

这里有很多类似的问题,但我找不到一个适用于我的案例,即使我可以调整一个类似的问题为我的案件工作,我没有迄今为止取得了成功。通过嵌套键合并词典列表

下面是简单的问题:

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

我想与常见合并辞典[ '操作'] [ '身份证']

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

谢谢!

+0

http://stackoverflow.com/questions/4235004/merge-nested-dictionaries-by-nested-keys但没有列表...我想要宁可使用itertools,如果可能的话 –

+0

你是什么意思“没有列表”?另外,这对我来说并不像'itertools'的一个好用例。我认为你需要一本字典来跟踪重复,因为它们被合并,除非你编写的代码充满了低效的线性搜索。 – senderle

回答

1

这似乎是一个很简单的问题,有一个实验位,你应该能够做到这一点:)

这里是我的版本,但也有解决问题的方法很多:

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() 
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'}}]