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 13, 2019 in Python by Mukesh
748 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 13, 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,840 points
1,022 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,090 points
713 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
951 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
1,075 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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,469 views
0 votes
1 answer
+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,790 points
4,128 views
0 votes
1 answer

How do I sort a dictionary by value?

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

answered Mar 13, 2019 in Python by Trisha
767 views
0 votes
1 answer

Accessing the index in 'for' loops?

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

answered Mar 13, 2019 in Python by Trisha
648 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP