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

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
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
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,520 points
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
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 May 20, 2019 in Python by Mohammad
• 3,210 points
0 votes
1 answer
+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 754 views
0 votes
0 answers
+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, 2019 in Python by Trisha
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