>> b = { "c" : 3, "d" : 4 }>>> a {'a': 1, 'b': 2}>>> b {'c': 3,">

Python “extend” for a dictionary

835    Asked by RutujaMishra in Python , Asked on Apr 9, 2021

Which is the best way to extend a dictionary with another one? For instance:

>>> a = { "a" : 1, "b" : 2 }
>>> b = { "c" : 3, "d" : 4 }
>>> a 
{'a': 1, 'b': 2}
>>> b 
{'c': 3, 'd': 4}
I'm looking for an operation to obtain this avoiding for loop:
{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 }
I wish to do something like:
a.extend(b) # This does not work

Answered by Rutuja Mishra

The best way to extend dictionary in python with another one dictionary is to use the dictionary comprehension with a dictionary mapping method:-

a = { "a" : 1, "b" : 2 }
b = { "c" : 3, "d" : 4 }
c={**a, **b}
print(c)
Note :
Python extend dictionary: The best way to extend a dictionary with another dictionary python is to use the dictionary comprehension with a dictionary mapping method:- a = { "a" : 1, "b" : 2 }.

Your Answer

Interviews

Parent Categories