Python Merge 2 Dictionaries without overwriting
Question: If a and b are 2 dictionaries:

    
    
    a = {'UK':'http://www.uk.com', 'COM':['http://www.uk.com','http://www.michaeljackson.com']}
    
    
    
    bb = {'Australia': 'http://www.australia.com', 'COM':['http://www.Australia.com', 'http://www.rafaelnadal.com','http://www.rogerfederer.com']}
    

I want to merge them to get

    
    
    {'Australia': ['http://www.australia.com'], 'COM': ['http://www.uk.com', 'http://www.michaeljackson.com', 'http://www.Australia.com', 'http://www.rafaelnadal.com', 'http://www.rogerfederer.com'], 'UK': ['http://www.uk.com']}
    

I want to union them i.e.

**How to do it in Python without overwwriting and replacing any value?**


Answer: Use a defaultdict:

    
    
    from collections import defaultdict
    d  = defaultdict(list)
    
    for dd in (a,bb):
        for k,v in dd.items():
            #Added this check to make extending work for cases where 
            #the value is a string.
            v = (v,) if isinstance(v,basestring) else v  #basestring is just str in py3k.
            d[k].extend(v)
    

(but this is pretty much what I told you in [my earlier
answer](http://stackoverflow.com/a/12389519/748858))

This now works if your input dictionaries look like

    
    
    {'Australia':['http://www.australia.com']}
    

or like:

    
    
    {'Australia':'http://www.australia.com'}
    

However, I would advise against the latter form. In general, I think it's a
good idea to keep all the keys/values of a dictionary looking the same (at
least if you want to treat all the items the same as in this question). That
means that if one value is a list, it's a good idea for _all of them_ to be a
list.

If you really insist on keeping things this way:

    
    
    d = {}
    for dd in (a,b):
       for k,v in dd.items():
           if(not isinstance(v,list)):
              v = [v]
           try:
              d[k].extend(v)
           except KeyError: #no key, no problem, just add it to the dict.
              d[k] = v
    

