How to merge two dictionaries in a single expression

0 votes
I have two dictionaries, and I want to write a single expression that returns these two dictionaries, merged. How can i do that please help.
Mar 12, 2019 in Python by Mukesh
153 views

1 answer to this question.

0 votes

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)

This way you can merge dictionaries in Python. Hope it helps. Please post if there are any other queries.

answered Mar 12, 2019 by Trisha

Related Questions In Python

0 votes
1 answer

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

Hello, For dictionaries x and y, z becomes a shallowly merged dictionary with ...READ MORE

answered Apr 13, 2020 in Python by Niroj
• 82,820 points
197 views
0 votes
0 answers

How to implement multiple try codes in a single block using Python?

Hi all, As per the title, I am ...READ MORE

Jan 14, 2019 in Python by Anirudh
• 2,080 points
172 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
296 views
0 votes
1 answer

How to select a single column in Pandas?

Pandas allows you to index the dataframe ...READ MORE

answered May 9, 2019 in Python by Suman
311 views
0 votes
2 answers
+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 2,352 views
0 votes
0 answers
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
1,762 views
0 votes
1 answer

How do I sort a dictionary by value?

If you construct a dictionary with the ...READ MORE

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

Accessing the index in 'for' loops?

Use enumerate to get the index with ...READ MORE

answered Mar 12, 2019 in Python by Trisha
108 views