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 in Python by Mukesh
39 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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 by Trisha

Related Questions In Python

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 in Python by Anirudh
• 2,050 points
18 views
0 votes
1 answer
0 votes
1 answer

How to select a single column in Pandas?

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

answered May 9 in Python by Suman
8 views
0 votes
1 answer

How can I write a program to add two numbers using functions in python?

def add(a,b):      return a + b #when i call ...READ MORE

answered 6 days ago in Python by Mohammad
• 1,400 points
9 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
27 views
+4 votes
6 answers
0 votes
1 answer

How do I sort a dictionary by value?

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

answered Mar 12 in Python by Trisha
6 views
0 votes
1 answer

Accessing the index in 'for' loops?

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

answered Mar 12 in Python by Trisha
8 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.