How do I merge two dictionaries in a single expression in Python?

0 votes

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place.

>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 10, 'c': 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{'a': 1, 'b': 10, 'c': 11}

How can I get that final merged dictionary in z, not x?

Apr 13 in Python by kartik
• 26,540 points
74 views

1 answer to this question.

0 votes

Hello,

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

  • 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)

Hope this works!!

Thank you!!

answered Apr 13 by Niroj
• 57,260 points

Related Questions In Python

0 votes
1 answer

How to merge two dictionaries in a single expression?

In Python 3.5 or greater: z = {**x, ...READ MORE

answered Mar 12, 2019 in Python by Trisha
92 views
0 votes
1 answer

how do i print only the last two letters in a string using regular expression in python?

$ to match the end of the ...READ MORE

answered Mar 15, 2019 in Python by Waseem
• 4,540 points
139 views
0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12, 2019 in Python by Nymeria
• 3,520 points
4,558 views
0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
1,908 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,349 views
0 votes
0 answers
0 votes
1 answer

How do I sort a list of dictionaries by a value of the dictionary?

Hello @kartik, import operator To sort the list of ...READ MORE

answered Apr 23 in Python by Niroj
• 57,260 points
66 views
0 votes
1 answer

How do I log a Python error with debug information?

Hii, In most applications, you won't be calling ...READ MORE

answered May 11 in Python by Niroj
• 57,260 points
74 views