1

I have two dictionaries:

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


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":"xyz" 
            } 

Also what if when we use list of dictionaries like : -

    first = {"phone": {
                "home": "(234) 442-4424"
            },
         "address":[{"home":""},{"office":""}]
            }
user3048148
  • 195
  • 2
  • 11

4 Answers4

4

Do second.update(first). Any keys in both will have their value set to the value in first and any keys that are in first but not second will be added to second.

El'endia Starman
  • 2,204
  • 21
  • 35
1

Update() will work, simply copy the second dict and apply the first one. So the value of the first will replace the second and not the reverse way.

first = {"phone": {"home": "(234) 442-4424"},"address":"xyz"}
second = {"phone": {"home": "(234) 442-5555","home1": "(234) 442-4424"},"address":{}}

# recursive deep update you can find here: http://stackoverflow.com/a/3233356/956660
import collections

def update(d, u):
    for k, v in u.iteritems():
        if isinstance(v, collections.Mapping):
            r = update(d.get(k, {}), v)
            d[k] = r
        else:
            d[k] = u[k]
    return d

third = second.copy()
update(third, first)

print(third)

{'phone': {'home': '(234) 442-4424', 'home1': '(234) 442-4424'}, 'address': 'xyz'}

Cyrbil
  • 6,341
  • 1
  • 24
  • 40
  • great it is working as required. Let me understand the logic which u have used. – user3048148 Nov 26 '15 at 05:26
  • Hi cyrbil, It is working fine but fail when we take list of dictionaries in it. I am beginners in python so unable to figure out how to fix this. I have updated the ticket. – user3048148 Dec 17 '15 at 09:03
  • Hi, please post another question for that. Addressing one issue at a time. – Cyrbil Dec 17 '15 at 10:17
0

If you want to just add the missing key/value pairs into the first dictionary, you can just add them to the first instead of creating a new dictionary.

first = {}
second = {}

for key in second.keys():
  if key not in first:
    first[key] = second[key]

Edit: your comment "it wont work with multilevel dictionary"

Actually, it will..technically speaking.

first = {"Person1" : {"Age": "26", "Name": "Person1", "Phone number": "XXXXXX"}}
second = {"Person1": {"Interests": "fishing"}, "Person2": {"Age": "26", "Name": "Person2", "Phone number": "XXXXXX"}}

In this case, the firstdict will get the Person2object, but will not change the Person1 object, as it is already there!

Arnab Datta
  • 5,356
  • 10
  • 41
  • 67
0

Assuming your dictionnaries have following structure:

  • each element is a dictionnary
  • values are either plain strings or dictionnaries

Assuming that the requirement is:

  • if a key exist only in one of the 2 elements to merge, keep its value
  • if a key exists in both elements:
    • if the value in first element is a plain string, keep its value
    • if the value in first element is a dict and the value in second is a string, keep value from first
    • if the values in both elements are dict merge them with priority to first

A possible code is then:

for k, v in first.iteritems():
    if isinstance(v, str):
        final[k] = v
    elif k in final:
        if isinstance(final[k], dict):
            final[k].update(first[k])
        else:
            final[k] = first[k]
    else:
        final[k] = first[k]
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252