Python Forum

Full Version: merging two dictionaries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
i am looking for a way to merge, combine, or add two dictionaries.  i would expect any key(s) in both would be in the result with the value from a designated dictionary (either the 1st or the 2nd).

i initially expected something like this to work:

d1 = {1:'one',2:'two'}
d2 = {2:'deux',3:'trois'}
d3 = d1 + d2
giving a result the same as:

d3 = {1:'one',2:'deux',3:'trois'}
the closest thing i could find in the documentation was the .update method.  but, .update would modify its self dictionary in place and not return the result, so:

d1 = {1:'one',2:'two'}
d2 = {2:'deux',3:'trois'}
d3 = d1.update(d2)
would not work, requiring code like:

d1 = {1:'one',2:'two'}
d2 = {2:'deux',3:'trois'}
d3 = copy.copy(d1)
d3.update(d2)
but in something like function call arguments this just gets messy.  any good ideas how to merge two dictionaries without creating an extra one in the code?
Doesn't this do what you want?
 
d3 = d1.copy().update(d2)
Quote:but in something like function call arguments this just gets messy. any good ideas how to merge two dictionaries without creating an extra one in the code?
put it in a function and call the function in the other functions params
(Oct-03-2017, 01:33 AM)buran Wrote: [ -> ]Doesn't this do what you want?
 
d3 = d1.copy().update(d2)

d3 = d1.copy()
d3.update(d2)
i am wanting to put it in a function call and not even have d3, like:

example_function(d1+d2)
https://bugs.python.org/issue6410
Well, support for dict.__add__ has been rejected long ago
You can always roll your own.  Just because it isn't in dict doesn't mean you can't use things that waddle and quack like dicts...

class Wrapper(dict):
    def __add__(self, other):
        final = {}
        for obj in [self, other]:
            final.update(obj)
        return final

a = Wrapper({1: 2, 3: 4})
b = Wrapper({1: 3, 5: 6})
print(a+b)
# {1: 3, 3: 4, 5: 6}
i was thinking maybe i'd have to roll my own.  i get that thought when i can't find it in the docs.  dict add is not hard.  pike has it (different terminology ... "mapping" is the direct term in pike).

so would dictmerge(a,b,...) be a good choice, or maybe dictmerge([a,b,...]), or maybe an implementation that can do it either way.  or would you rather see a different name?  dictjoin?
Well, it's is a good idea in general to be created Merge class to handle all obj + obj statements for all of these types which don't have __add__ method into the type class definition.
>>> d1 = {1:'one',2:'two'}
>>> d2 = {2:'deux',3:'trois'}
>>> d3 = {**d1, **d2}
>>> d3
{1: 'one', 2: 'deux', 3: 'trois'}
Pages: 1 2