-2

I have two dictionaries:

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


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

I want merge two dictionaries first over second, meaning the first dictionary doesn't lose its previous values and only the missing key values are added into first.

The final dictionary should look like this:-

final = {"phone": {
            "home": "(234) 442-4424",
            "home1": "(234) 442-4424"
        },
     "address":[{"home":""},{"office":""}]
        } 
user3048148
  • 195
  • 2
  • 11
  • 1
    Have you tried already? What have you tried, and what didn't work? – SiHa Dec 17 '15 at 10:56
  • plz check this link it is working fine for dictioanry http://stackoverflow.com/questions/33912772/merge-two-dictionaries-and-persist-the-values-of-first-dictionaries but dont give desired result when dictionary have list of items – user3048148 Dec 17 '15 at 11:01
  • The last answer I gave you merge recursively **dictionnaries**, to merge dict that contain arrays, you need to check object type (dict or array) and merge accordingly and recursively. Please show some research and try, this post is a series of 3 other posts where you ask without even trying. – Cyrbil Dec 17 '15 at 11:31
  • Old questions were [1](http://stackoverflow.com/q/33916875/956660) and [2](http://stackoverflow.com/q/33912772/956660). – Cyrbil Dec 17 '15 at 11:35
  • If you dont have answer then leave it. – user3048148 Dec 17 '15 at 11:36
  • You have asked to create new question so I have did. Unfortunately you dont have answer. – user3048148 Dec 17 '15 at 11:38
  • I have checked the object type list but unable to get desired result. – user3048148 Dec 17 '15 at 11:40

2 Answers2

0

I have solved this by using following method: My actual data was :

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

and our mergeDict function :

     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

This merge function gives us what was required. Please suggest if I could optimize further.

user3048148
  • 195
  • 2
  • 11
-1

You could use first.extend(second). But maybe you have to iterate over the children of the first dictionary and extend every child separately.

Randrian
  • 1,055
  • 12
  • 25