将两个字典与元素列表合并,并保留第一个字典

时间:2015-12-17 10:53:58

标签: python list dictionary

我有两本词典:

first = {"phone": {
            "home": "(234) 442-4424"
        },
     "address":[{"home":""},{"office":""}]
        }


second = {"phone": {
            "home": "(234) 442-4424",
            "home1": "(234) 442-4424"
        },
     "address":[]
        } 

我希望首先合并两个词典超过第二个,这意味着第一个词典不会丢失其先前的值,只会将缺少的键值添加到第一个词典中。

最终字典应如下所示: -

final = {"phone": {
            "home": "(234) 442-4424",
            "home1": "(234) 442-4424"
        },
     "address":[{"home":""},{"office":""}]
        } 

2 个答案:

答案 0 :(得分:0)

我通过以下方法解决了这个问题: 我的实际数据是:

first_json = {"basic_info":[{"indexPos": "0", "isUpper": "1", "placeHolder": "NAME THIS CARD (Required)", "value": "ddd", "keyName": "CardName"},{"indexPos": "0", "isUpper": "1", "placeHolder": "NAME THIS CARD (Required)sddd", "value": "", "keyName": "CardName11"}]}

second_json = {"basic_info": [{"indexPos": "0", "isUpper": "1", "placeHolder": "NAME THIS CARD (Required)sddd", "value": "wwwwwwwwww", "keyName": "CardName"},{"indexPos": "0", "isUpper": "1", "placeHolder": "NAME THIS CARD (Required)sddd", "value": "dsfsdfd", "keyName": "CardName11"}]}

third_json = second_json.copy()

self.mergeDict(third_json, first_json)
print third_json

和我们的mergeDict函数:

     def mergeDict(self,s, f):
      for k, v in f.iteritems():
        if isinstance(v, collections.Mapping):
            r = self.mergeDict(s.get(k, {}), v)
            s[k] = r
        elif isinstance(v, list):
            result = []
            """ TODO : optimization """

            if k == 'basic_info':
               for  valf in v:
                    if 'keyName' in valf:
                        for vals in s.get(k, {}):
                                if valf['keyName'] in vals.values() and vals['value'] !="" and valf['value'] == "":
                                    valf['value'] = vals['value']
                        result.append(valf)
               """ Reverse loop is for check  extra data in second business card """          
               for vals1 in s.get(k, {}):
                       if 'keyName' in vals1:
                          check = 0  
                          for valf1 in v:
                              if vals1['keyName'] in valf1.values():
                                 check = 1
                          if not check:
                              result.append(vals1)                            
            else:
               v.extend(s.get(k, {})) 
               for myDict in v:
                    if myDict not in result:
                        result.append(myDict)

            s[k] = result    
        else:
            #------------- If the key is blank in first business card then second business card value assign to it -----#
            if not v and s.get(k, {}):
                #f[k] = s.get(k, {})
                pass
            else:    
                s[k] = f[k]
    return s

这个合并功能为我们提供了所需要的功能。请建议我是否可以进一步优化。

答案 1 :(得分:-1)

你可以使用first.extend(第二个)。但也许你必须迭代第一本字典的孩子并分别扩展每个孩子。