in Technology by
How do I merge two dictionaries in a single expression in Python (taking union of dictionaries)?

1 Answer

0 votes
by

For dictionaries x and y, z becomes a shallowly merged dictionary with values from y replacing those from x.

  • In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method:

    z = x | y          # NOTE: 3.9+ ONLY
    
  • In Python 3.5 or greater:

    z = {**x, **y}
    
  • In Python 2, (or 3.4 or lower) write a function:

    def merge_two_dicts(x, y):
        z = x.copy()   # start with x's keys and values
        z.update(y)    # modifies z with y's keys and values & returns None
        return z
    

    and now:

    z = merge_two_dicts(x, y)
    

Explanation

Say you have two dictionaries and you want to merge them into a new dict without altering the original dictionaries:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

The desired result is to get a new dictionary (z) with the values merged, and the second dictionary's values overwriting those from the first.

>>> z
{'a': 1, 'b': 3, 'c': 4}

A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is

z = {**x, **y}

And it is indeed a single expression.

Note that we can merge in with literal notation as well:

z = {**x, 'foo': 1, 'bar': 2, **y}

and now:

>>> z
{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}

It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into What's New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

z = x.copy()
z.update(y) # which returns None since it mutates z

In both approaches, y will come second and its values will replace x's values, thus 'b' will point to 3 in our final result.

Not yet on Python 3.5, but want a single expression

If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function:

def merge_two_dicts(x, y):
    """Given two dictionaries, merge them into a new dict as a shallow copy."""
    z = x.copy()
    z.update(y)
    return z

and then you have a single expression:

z = merge_two_dicts(x, y)

You can also make a function to merge an undefined number of dictionaries, from zero to a very large number:

def merge_dicts(*dict_args):
    """
    Given any number of dictionaries, shallow copy and merge into a new dict,
    precedence goes to key-value pairs in latter dictionaries.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries a to g:

z = merge_dicts(a, b, c, d, e, f, g) 

and key-value pairs in g will take precedence over dictionaries a to f, and so on.

Related questions

0 votes
    I want to combine two views in one dashboard in google analytics report. I want the tracked buttons up ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 19, 2022 in Education by JackTerrance
0 votes
    I want to combine two views in one dashboard in google analytics report. I want the tracked buttons up ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked May 6, 2022 in Education by JackTerrance
0 votes
    I want each item to be sorted by a specific property value from a list of dictionaries I have. Take the ... When sorted by name Select the correct answer from above options...
asked Jan 20, 2022 in Education by JackTerrance
0 votes
    I have two different source structure tables, but I want to load into single target table? How do I go about it? Explain in detail through mapping flow....
asked Mar 28, 2021 by JackTerrance
0 votes
    Select * from OPENQUERY (PORTAL, ''SELECT st.last AS "Last Name", st.first AS "First Name", ct. ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 17, 2022 in Education by JackTerrance
0 votes
    I switched from Perl to Python about a year ago and haven't looked back. There is only one idiom ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 21, 2022 in Education by JackTerrance
0 votes
    I switched from Perl to Python about a year ago and haven't looked back. There is only one idiom ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 20, 2022 in Education by JackTerrance
0 votes
    E.x. listA = [9,10,11] listB = [12,13,14] Expected outcome: >>> concatenated list [9,10,11,12,13,14] Select the correct answer from above options...
asked Jan 20, 2022 in Education by JackTerrance
0 votes
    Can anyone tell me how will taking this course help you achieve your career goals Python? Select the correct answer from above options...
asked Jan 19, 2022 in Education by JackTerrance
0 votes
    tableone a |b| c -------- a1 | |c1 a2 | |c2 a3 | |c3 tabletwo a | b ----- ... JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 23, 2022 in Education by JackTerrance
0 votes
    do you think the following two expression are the same if yes write the output if not justify your answer X=int(22/7) X=(22.0/7) Select the correct answer from above options...
asked Dec 13, 2021 in Education by JackTerrance
0 votes
    I am trying to merge 2 data frames by using the id and then trying to save the result in the JSON file. | |id|a|b ... |3|15|3, 12|6, 15 Select the correct answer from above options...
asked Jan 11, 2022 in Education by JackTerrance
0 votes
    The _______operation performs a set union of two similarly structured tables (a) Union (b) Join (c) ... , Database Interview Questions and Answers for Freshers and Experience...
asked Oct 11, 2021 in Education by JackTerrance
0 votes
    1. Name the term which is used to join two separate arrays into a single array. 2.How are the following ... ii) primitive type data Select the correct answer from above options...
asked Dec 13, 2021 in Education by JackTerrance
0 votes
    I have two data frames with the closest matching DateTime index, sometimes matching. An object is to merge two of ... I achieve this? Select the correct answer from above options...
asked Jan 19, 2022 in Education by JackTerrance
...